import { Model, DataTypes, Sequelize } from 'sequelize';

export interface FffClearanceAttributes {
    id: string;
    fnfId: string;
    department: string; // 16 Functional units: Sales, Service, Spares, Finance, Marketing, HR, etc.
    clearedBy: string; // User ID
    status: string; // 'Pending', 'Cleared', 'Rejected', 'N/A'
    remarks: string | null;
    clearedAt: Date | null;
    documentId: string | null; // For NOC upload
    supportingDocument: string | null;
}

export interface FffClearanceInstance extends Model<FffClearanceAttributes>, FffClearanceAttributes { }

export default (sequelize: Sequelize) => {
    const FffClearance = sequelize.define<FffClearanceInstance>('FffClearance', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        fnfId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'fnf_settlements',
                key: 'id'
            }
        },
        department: {
            type: DataTypes.STRING,
            allowNull: false
        },
        clearedBy: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'users',
                key: 'id'
            }
        },
        status: {
            type: DataTypes.STRING,
            defaultValue: 'Pending'
        },
        remarks: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        clearedAt: {
            type: DataTypes.DATE,
            allowNull: true
        },
        documentId: {
            type: DataTypes.UUID,
            allowNull: true
        },
        supportingDocument: {
            type: DataTypes.STRING,
            allowNull: true
        }
    }, {
        tableName: 'fff_clearances',
        timestamps: true
    });

    (FffClearance as any).associate = (models: any) => {
        FffClearance.belongsTo(models.FnF, { foreignKey: 'fnfId', as: 'fnfSettlement' });
        FffClearance.belongsTo(models.User, { foreignKey: 'clearedBy', as: 'clearanceOfficer' });
    };

    return FffClearance;
};
