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

export interface PermissionAttributes {
    id: string;
    permissionCode: string;
    permissionName: string;
    permissionCategory: string;
    module: string;
    permissionType: string;
    action: string;
    description: string | null;
}

export interface PermissionInstance extends Model<PermissionAttributes>, PermissionAttributes { }

export default (sequelize: Sequelize) => {
    const Permission = sequelize.define<PermissionInstance>('Permission', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        permissionCode: {
            type: DataTypes.STRING,
            unique: true,
            allowNull: false
        },
        permissionName: {
            type: DataTypes.STRING,
            allowNull: false
        },
        permissionCategory: {
            type: DataTypes.STRING,
            allowNull: false,
            defaultValue: 'GENERAL'
        },
        module: {
            type: DataTypes.STRING,
            allowNull: false
        },
        permissionType: {
            type: DataTypes.STRING,
            allowNull: false
        },
        action: {
            type: DataTypes.STRING,
            allowNull: false
        },
        description: {
            type: DataTypes.TEXT,
            allowNull: true
        }
    }, {
        tableName: 'permissions',
        timestamps: true,
        updatedAt: false
    });

    (Permission as any).associate = (models: any) => {
        Permission.hasMany(models.RolePermission, {
            foreignKey: 'permissionId',
            as: 'rolePermissions'
        });
        Permission.belongsToMany(models.Role, {
            through: models.RolePermission,
            foreignKey: 'permissionId',
            otherKey: 'roleId',
            as: 'roles'
        });
    };

    return Permission;
};
