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

export interface LocationAttributes {
    id: string;
    name: string;
    districtId: string | null;
    city?: string | null;
    isOpportunity?: boolean;
    openFrom?: Date | null;
    openTo?: Date | null;
    description?: string | null;
}

export interface LocationInstance extends Model<LocationAttributes>, LocationAttributes { }

export default (sequelize: Sequelize) => {
    const Location = sequelize.define<LocationInstance>('Location', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        name: {
            type: DataTypes.STRING,
            allowNull: false
        },
        districtId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'districts',
                key: 'id'
            }
        },
        city: {
            type: DataTypes.STRING,
            allowNull: true
        },
        isOpportunity: {
            type: DataTypes.BOOLEAN,
            defaultValue: true
        },
        openFrom: {
            type: DataTypes.DATE,
            allowNull: true
        },
        openTo: {
            type: DataTypes.DATE,
            allowNull: true
        },
        description: {
            type: DataTypes.TEXT,
            allowNull: true
        }
    }, {
        tableName: 'locations',
        timestamps: true,
        indexes: [
            { fields: ['districtId'] },
            { unique: true, fields: ['name', 'districtId'] }
        ]
    });

    (Location as any).associate = (models: any) => {
        Location.belongsTo(models.District, { foreignKey: 'districtId', as: 'district' });
        
        // These can have detailed opportunities if needed in future
        Location.hasMany(models.Opportunity, { foreignKey: 'areaId', as: 'opportunities' }); 
    };

    return Location;
};
