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

export interface OpportunityAttributes {
    id: string;
    districtId: string;
    areaId?: string | null;
    city: string;
    opportunityType: string;
    capacity: string;
    priority: string;
    openFrom: Date | null;
    openTo: Date | null;
    status: string;
    notes: string | null;
    createdBy: string | null;
}

export interface OpportunityInstance extends Model<OpportunityAttributes>, OpportunityAttributes { }

export default (sequelize: Sequelize) => {
    const Opportunity = sequelize.define<OpportunityInstance>('Opportunity', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        districtId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'districts',
                key: 'id'
            }
        },
        areaId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'locations',
                key: 'id'
            }
        },
        city: {
            type: DataTypes.STRING,
            allowNull: false
        },
        opportunityType: {
            type: DataTypes.STRING,
            allowNull: false
        },
        capacity: {
            type: DataTypes.STRING,
            allowNull: false
        },
        priority: {
            type: DataTypes.STRING,
            allowNull: false
        },
        openFrom: {
            type: DataTypes.DATE,
            allowNull: true
        },
        openTo: {
            type: DataTypes.DATE,
            allowNull: true
        },
        status: {
            type: DataTypes.STRING,
            defaultValue: 'active'
        },
        notes: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        createdBy: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'users',
                key: 'id'
            }
        }
    }, {
        tableName: 'opportunities',
        timestamps: true
    });

    (Opportunity as any).associate = (models: any) => {
        Opportunity.belongsTo(models.District, { foreignKey: 'districtId', as: 'district' });
        Opportunity.belongsTo(models.Location, { foreignKey: 'areaId', as: 'area' });
        Opportunity.belongsTo(models.User, { foreignKey: 'createdBy', as: 'creator' });
        Opportunity.hasMany(models.Application, { foreignKey: 'opportunityId', as: 'applications' });
    };

    return Opportunity;
};
