import { Sequelize, DataTypes, Model, Optional } from 'sequelize';
import { UserAttributes } from './User';

export interface ClientMasterAttributes {
    id: number;
    client_name: string;
    is_active: boolean;
    created_by?: number;
}

interface ClientMasterCreationAttributes extends Optional<ClientMasterAttributes, 'id'> {}

export class ClientMaster
    extends Model<ClientMasterAttributes, ClientMasterCreationAttributes>
    implements ClientMasterAttributes 
{
    public static associate(models: any): void {
       
        ClientMaster.belongsTo(models.User, {
            foreignKey: 'created_by',
            as: 'creator',
          });
    }
    public id!: number;
    public client_name!: string;
    public is_active!: boolean;
    public created_by?: number;
    public creator?: UserAttributes;

    public toJSON(): ClientMasterAttributes & {
        creator?: UserAttributes;
    } 
    {
        return {
            ...super.toJSON(),
            id: this.id,
            client_name: this.client_name,
            is_active: this.is_active,
            created_by: this.created_by,
            creator: this.creator,
        };
    }
}

export default (sequelize: Sequelize, dataTypes: typeof DataTypes) => {
    ClientMaster.init(
        {
            id: {
                type: dataTypes.INTEGER,
                autoIncrement: true,
                primaryKey: true,
            },
            client_name: {
                type: dataTypes.STRING,
                allowNull: false,
            },
            created_by: {
                type: dataTypes.INTEGER,
                allowNull: true,
                references: {
                    model: 'Users',
                    key: 'id',
                },
            },
            is_active: {
                type: dataTypes.BOOLEAN,
                allowNull: false,
                defaultValue: true,
            },
        },
        {
            sequelize,
            modelName: 'ClientMaster',
            tableName: 'client_masters',
            timestamps: true,
        }
    );

    return ClientMaster;
};