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

export interface LoiRequestAttributes {
    id: string;
    applicationId: string | null;
    status: string;
    requestedBy: string | null;
    approvedAt: Date | null;
    approvedBy: string | null;
}

export interface LoiRequestInstance extends Model<LoiRequestAttributes>, LoiRequestAttributes { }

export default (sequelize: Sequelize) => {
    const LoiRequest = sequelize.define<LoiRequestInstance>('LoiRequest', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        applicationId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'applications',
                key: 'id'
            }
        },
        status: {
            type: DataTypes.STRING,
            defaultValue: 'pending'
        },
        requestedBy: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'users',
                key: 'id'
            }
        },
        approvedAt: {
            type: DataTypes.DATE,
            allowNull: true
        },
        approvedBy: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'users',
                key: 'id'
            }
        }
    }, {
        tableName: 'loi_requests',
        timestamps: true
    });

    (LoiRequest as any).associate = (models: any) => {
        LoiRequest.belongsTo(models.Application, { foreignKey: 'applicationId', as: 'application' });
        LoiRequest.belongsTo(models.User, { foreignKey: 'requestedBy', as: 'requester' });
        LoiRequest.belongsTo(models.User, { foreignKey: 'approvedBy', as: 'approver' });

        LoiRequest.hasMany(models.LoiApproval, { foreignKey: 'requestId', as: 'approvals' });
        LoiRequest.hasMany(models.LoiDocumentGenerated, { foreignKey: 'requestId', as: 'generatedDocuments' });
    };

    return LoiRequest;
};
