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

export interface DealerCodeAttribute {
    id: string;
    dealerCode: string;
    applicationId: string | null;
    salesCode: string | null;
    serviceCode: string | null;
    gmaCode: string | null;
    gearCode: string | null;
    sapMasterId: string | null;
    status: string;
    generatedAt: Date;
    generatedBy: string | null;
}

export interface DealerCodeInstance extends Model<DealerCodeAttribute>, DealerCodeAttribute { }

export default (sequelize: Sequelize) => {
    const DealerCode = sequelize.define<DealerCodeInstance>('DealerCode', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        dealerCode: {
            type: DataTypes.STRING,
            unique: true,
            allowNull: false
        },
        applicationId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'applications',
                key: 'id'
            }
        },
        salesCode: {
            type: DataTypes.STRING,
            allowNull: true
        },
        serviceCode: {
            type: DataTypes.STRING,
            allowNull: true
        },
        gmaCode: {
            type: DataTypes.STRING,
            allowNull: true
        },
        gearCode: {
            type: DataTypes.STRING,
            allowNull: true
        },
        sapMasterId: {
            type: DataTypes.STRING,
            allowNull: true
        },
        status: {
            type: DataTypes.STRING,
            defaultValue: 'active'
        },
        generatedAt: {
            type: DataTypes.DATE,
            defaultValue: DataTypes.NOW
        },
        generatedBy: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'users',
                key: 'id'
            }
        }
    }, {
        tableName: 'dealer_codes',
        timestamps: true,
        updatedAt: false
    });

    (DealerCode as any).associate = (models: any) => {
        DealerCode.belongsTo(models.User, { foreignKey: 'generatedBy', as: 'generator' });
        DealerCode.hasOne(models.Dealer, { foreignKey: 'dealerCodeId', as: 'dealer' });
        DealerCode.belongsTo(models.Application, { foreignKey: 'applicationId', as: 'application' });
    };

    return DealerCode;
};
