import { Model, DataTypes, Sequelize } from 'sequelize';
import { ROLES, REGIONS } from '../../../common/config/constants.js';

export interface UserAttributes {
    id: string;
    employeeId: string | null;
    email: string;
    password?: string;
    fullName: string;
    mobileNumber: string | null;
    department: string | null;
    designation: string | null;
    roleCode: string | null;
    districtId: string | null; 
    zoneId: string | null;
    regionId: string | null;
    stateId: string | null;
    dealerId: string | null;
    isActive: boolean;
    isExternal: boolean;
    ssoProvider: string | null;
    status: string;
    lastLogin: Date | null;
}

export interface UserInstance extends Model<UserAttributes>, UserAttributes { }

export default (sequelize: Sequelize) => {
    const User = sequelize.define<UserInstance>('User', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        employeeId: {
            type: DataTypes.STRING,
            unique: true,
            allowNull: true
        },
        email: {
            type: DataTypes.STRING,
            unique: true,
            allowNull: false,
            validate: {
                isEmail: true
            }
        },
        password: {
            type: DataTypes.STRING,
            allowNull: true
        },
        fullName: {
            type: DataTypes.STRING,
            allowNull: false
        },
        mobileNumber: {
            type: DataTypes.STRING,
            allowNull: true
        },
        department: {
            type: DataTypes.STRING,
            allowNull: true
        },
        designation: {
            type: DataTypes.STRING,
            allowNull: true
        },
        roleCode: {
            type: DataTypes.STRING,
            allowNull: true
        },
        districtId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: { model: 'districts', key: 'id' }
        },
        zoneId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: { model: 'zones', key: 'id' }
        },
        regionId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: { model: 'regions', key: 'id' }
        },
        stateId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: { model: 'states', key: 'id' }
        },
        dealerId: {
            type: DataTypes.UUID,
            allowNull: true
        },
        isActive: {
            type: DataTypes.BOOLEAN,
            defaultValue: true
        },
        isExternal: {
            type: DataTypes.BOOLEAN,
            defaultValue: false
        },
        ssoProvider: {
            type: DataTypes.STRING,
            allowNull: true
        },
        status: {
            type: DataTypes.STRING,
            defaultValue: 'active'
        },
        lastLogin: {
            type: DataTypes.DATE,
            allowNull: true
        }
    }, {
        tableName: 'users',
        timestamps: true,
        indexes: [
            { fields: ['email'] },
            { fields: ['employeeId'] },
            { fields: ['roleCode'] }
        ]
    });

    (User as any).associate = (models: any) => {
        User.belongsTo(models.Role, {
            foreignKey: 'roleCode',
            targetKey: 'roleCode',
            as: 'role'
        });
        User.hasMany(models.UserRole, { foreignKey: 'userId', as: 'userRoles' });
        User.hasMany(models.UserRole, { foreignKey: 'assignedBy', as: 'assignedRoles' });
        
        // Link to District (Parent Territory)
        User.belongsTo(models.District, { foreignKey: 'districtId', as: 'district' });
        
        // Role-specific managed districts (pointing to District model now)
        User.hasMany(models.District, { foreignKey: 'asmId', as: 'managedAsmDistricts' });
        User.hasMany(models.District, { foreignKey: 'ddAmId', as: 'managedAreaDistricts' });
        User.hasMany(models.District, { foreignKey: 'zmId', as: 'managedZmDistricts' });
        
        User.belongsTo(models.Zone, { foreignKey: 'zoneId', as: 'zone' });
        User.belongsTo(models.Region, { foreignKey: 'regionId', as: 'region' });
        User.belongsTo(models.State, { foreignKey: 'stateId', as: 'state' });

        User.hasMany(models.AuditLog, { foreignKey: 'userId', as: 'auditLogs' });
        User.belongsTo(models.Dealer, { foreignKey: 'dealerId', as: 'dealerProfile' });
        User.hasMany(models.Dealer, { foreignKey: 'asmId', as: 'assignedDealers' });
        User.hasMany(models.Outlet, { foreignKey: 'dealerId', as: 'outlets' });
    };

    return User;
};
