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

export interface ResignationAttributes {
    id: string;
    resignationId: string;
    outletId: string;
    dealerId: string;
    resignationType: typeof RESIGNATION_TYPES[keyof typeof RESIGNATION_TYPES];
    lastOperationalDateSales: string;
    lastOperationalDateServices: string;
    reason: string;
    additionalInfo: string | null;
    currentStage: typeof RESIGNATION_STAGES[keyof typeof RESIGNATION_STAGES];
    status: string;
    progressPercentage: number;
    submittedOn: Date;
    documents: any[];
    timeline: any[];
    rejectionReason: string | null;
    departmentalClearances: Record<string, {
        status: 'Pending' | 'Cleared' | 'Dues';
        amount?: number;
        /** Receivable = amount owed by dealer; Recovery kept for legacy JSON only */
        type?: 'Payable' | 'Receivable' | 'Recovery';
        remarks?: string;
        updatedAt?: string;
        updatedBy?: string;
    }> | null;
}

export interface ResignationInstance extends Model<ResignationAttributes>, ResignationAttributes { }

export default (sequelize: Sequelize) => {
    const Resignation = sequelize.define<ResignationInstance>('Resignation', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        resignationId: {
            type: DataTypes.STRING,
            unique: true,
            allowNull: false
        },
        outletId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'outlets',
                key: 'id'
            }
        },
        dealerId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'users',
                key: 'id'
            }
        },
        resignationType: {
            type: DataTypes.ENUM(...Object.values(RESIGNATION_TYPES)),
            allowNull: false
        },
        lastOperationalDateSales: {
            type: DataTypes.DATEONLY,
            allowNull: false
        },
        lastOperationalDateServices: {
            type: DataTypes.DATEONLY,
            allowNull: false
        },
        reason: {
            type: DataTypes.TEXT,
            allowNull: false
        },
        additionalInfo: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        currentStage: {
            type: DataTypes.ENUM(...Object.values(RESIGNATION_STAGES)),
            defaultValue: RESIGNATION_STAGES.ASM
        },
        status: {
            type: DataTypes.STRING,
            defaultValue: 'Pending'
        },
        progressPercentage: {
            type: DataTypes.INTEGER,
            defaultValue: 0
        },
        submittedOn: {
            type: DataTypes.DATE,
            defaultValue: DataTypes.NOW
        },
        documents: {
            type: DataTypes.JSON,
            defaultValue: []
        },
        timeline: {
            type: DataTypes.JSON,
            defaultValue: []
        },
        rejectionReason: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        departmentalClearances: {
            type: DataTypes.JSON,
            defaultValue: {}
        }
    }, {
        tableName: 'resignations',
        timestamps: true,
        indexes: [
            { fields: ['resignationId'] },
            { fields: ['outletId'] },
            { fields: ['dealerId'] },
            { fields: ['currentStage'] },
            { fields: ['status'] }
        ]
    });

    (Resignation as any).associate = (models: any) => {
        Resignation.belongsTo(models.Outlet, {
            foreignKey: 'outletId',
            as: 'outlet'
        });
        Resignation.belongsTo(models.User, {
            foreignKey: 'dealerId',
            as: 'dealer'
        });
        Resignation.hasMany(models.ResignationDocument, {
            foreignKey: 'resignationId',
            as: 'uploadedDocuments'
        });
        Resignation.hasMany(models.Worknote, {
            foreignKey: 'requestId',
            as: 'worknotes',
            scope: {
                requestType: 'resignation'
            },
            constraints: false
        });
        Resignation.hasOne(models.FnF, {
            foreignKey: 'resignationId',
            as: 'settlement'
        });
        Resignation.hasMany(models.RequestParticipant, {
            foreignKey: 'requestId',
            as: 'participants',
            scope: { requestType: 'resignation' },
            constraints: false
        });
    };

    return Resignation;
};
