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

export interface ProjectMasterAttributes {
    id: number;
    project: string;
    client_id: number;
    is_active: boolean;
    created_by?: number;
}

interface ProjectMasterCreationAttributes extends Optional<ProjectMasterAttributes, 'id'> {}

export class ProjectMaster
    extends Model<ProjectMasterAttributes, ProjectMasterCreationAttributes>
    implements ProjectMasterAttributes 
{
    public static associate(models: any): void {
        ProjectMaster.belongsTo(models.ClientMaster, {
            foreignKey: 'client_id',
            as: 'client',
            targetKey: 'id',
        });
        ProjectMaster.belongsTo(models.User, {
            foreignKey: 'created_by',
            as: 'creator',
          });
        ProjectMaster.hasMany(models.ProjectStaffing, {
            foreignKey: 'project_id',
            as: 'staffings'
        })
    }
    public id!: number;
    public project!: string;
    public client_id!: number;
    public is_active!: boolean;
    public client?: ClientMasterAttributes;
    public created_by?: number;
    public creator?: UserAttributes;


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

        };
    }
}

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

    return ProjectMaster;
};