import crypto from 'crypto';
import bcrypt from 'bcrypt';
import {
  DataTypes,
  Model,
  type CreationOptional,
  type InferAttributes,
  type InferCreationAttributes,
  type NonAttribute,
  type Sequelize,
} from 'sequelize';
import config from '@/shared/config';
import {
  USER_NAME_PREFIX_VALUES,
  type UserNamePrefix,
} from '@/shared/constants/users';
import type { Db } from '@/db/types';
import type {
  BelongsToGetAssociationMixin,
  BelongsToSetAssociationMixin,
  BelongsToManyGetAssociationsMixin,
  BelongsToManySetAssociationsMixin,
  HasManyGetAssociationsMixin,
  HasManySetAssociationsMixin,
} from 'sequelize';
import type { Campuses } from './campuses';
import type { File } from './file';
import type { Messages } from './messages';
import type { Organizations } from './organizations';
import type { Permissions } from './permissions';
import type { Roles } from './roles';
import type { Staff } from './staff';

const providers = config.providers;

export class Users extends Model<
  InferAttributes<Users>,
  InferCreationAttributes<Users>
> {
  declare id: CreationOptional<string>;
  declare name_prefix: CreationOptional<UserNamePrefix | null>;
  declare firstName: CreationOptional<string | null>;
  declare lastName: CreationOptional<string | null>;
  declare phoneNumber: CreationOptional<string | null>;
  declare email: string;
  declare disabled: CreationOptional<boolean>;
  declare password: CreationOptional<string | null>;
  declare emailVerified: CreationOptional<boolean>;
  declare emailVerificationToken: CreationOptional<string | null>;
  declare emailVerificationTokenExpiresAt: CreationOptional<Date | null>;
  declare passwordResetToken: CreationOptional<string | null>;
  declare passwordResetTokenExpiresAt: CreationOptional<Date | null>;
  declare provider: CreationOptional<string | null>;
  declare importHash: CreationOptional<string | null>;
  declare organizationId: CreationOptional<string | null>;
  /** Campus scope for campus-bound roles (Workstream 3 §3.1). Nullable. */
  declare campusId: CreationOptional<string | null>;
  declare createdById: CreationOptional<string | null>;
  declare updatedById: CreationOptional<string | null>;
  declare createdAt: CreationOptional<Date>;
  declare updatedAt: CreationOptional<Date>;
  declare deletedAt: CreationOptional<Date | null>;

  // Eager-loaded associations (populated by `include`, not stored attributes).
  declare app_role?: NonAttribute<Roles>;
  declare organizations?: NonAttribute<Organizations>;
  declare campus?: NonAttribute<Campuses>;
  declare staff_user?: NonAttribute<Staff[]>;
  declare custom_permissions?: NonAttribute<Permissions[]>;

  declare getCustom_permissions: BelongsToManyGetAssociationsMixin<Permissions>;
  declare setCustom_permissions: BelongsToManySetAssociationsMixin<Permissions, string>;
  declare getCustom_permissions_filter: BelongsToManyGetAssociationsMixin<Permissions>;
  declare setCustom_permissions_filter: BelongsToManySetAssociationsMixin<Permissions, string>;
  declare getStaff_user: HasManyGetAssociationsMixin<Staff>;
  declare setStaff_user: HasManySetAssociationsMixin<Staff, string>;
  declare getMessages_sent_by: HasManyGetAssociationsMixin<Messages>;
  declare setMessages_sent_by: HasManySetAssociationsMixin<Messages, string>;
  declare getApp_role: BelongsToGetAssociationMixin<Roles>;
  declare setApp_role: BelongsToSetAssociationMixin<Roles, string>;
  declare getOrganizations: BelongsToGetAssociationMixin<Organizations>;
  declare setOrganizations: BelongsToSetAssociationMixin<Organizations, string>;
  declare getCampus: BelongsToGetAssociationMixin<Campuses>;
  declare setCampus: BelongsToSetAssociationMixin<Campuses, string>;
  declare getAvatar: HasManyGetAssociationsMixin<File>;
  declare setAvatar: HasManySetAssociationsMixin<File, string>;
  declare getCreatedBy: BelongsToGetAssociationMixin<Users>;
  declare setCreatedBy: BelongsToSetAssociationMixin<Users, string>;
  declare getUpdatedBy: BelongsToGetAssociationMixin<Users>;
  declare setUpdatedBy: BelongsToSetAssociationMixin<Users, string>;

  static associate(db: Db): void {
    db.users.belongsToMany(db.permissions, {
      as: 'custom_permissions',
      foreignKey: {
        name: 'users_custom_permissionsId',
      },
      constraints: false,
      through: 'usersCustom_permissionsPermissions',
    });

    db.users.belongsToMany(db.permissions, {
      as: 'custom_permissions_filter',
      foreignKey: {
        name: 'users_custom_permissionsId',
      },
      constraints: false,
      through: 'usersCustom_permissionsPermissions',
    });

    db.users.hasMany(db.staff, {
      as: 'staff_user',
      foreignKey: {
        name: 'userId',
      },
      constraints: false,
    });

    db.users.hasMany(db.messages, {
      as: 'messages_sent_by',
      foreignKey: {
        name: 'sent_byId',
      },
      constraints: false,
    });

    db.users.belongsTo(db.roles, {
      as: 'app_role',
      foreignKey: {
        name: 'app_roleId',
      },
      constraints: false,
    });

    db.users.belongsTo(db.organizations, {
      as: 'organizations',
      foreignKey: {
        name: 'organizationId',
      },
      constraints: false,
    });

    db.users.belongsTo(db.campuses, {
      as: 'campus',
      foreignKey: {
        name: 'campusId',
      },
      constraints: false,
    });

    db.users.hasMany(db.file, {
      as: 'avatar',
      foreignKey: 'belongsToId',
      constraints: false,
      scope: {
        belongsTo: db.users.getTableName(),
        belongsToColumn: 'avatar',
      },
    });

    db.users.belongsTo(db.users, {
      as: 'createdBy',
    });

    db.users.belongsTo(db.users, {
      as: 'updatedBy',
    });
  }
}

function trimStringFields(user: Users): Users {
  user.email = user.email.trim();

  user.firstName = user.firstName ? user.firstName.trim() : null;

  user.lastName = user.lastName ? user.lastName.trim() : null;

  return user;
}

export default function (sequelize: Sequelize): typeof Users {
  Users.init(
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      name_prefix: {
        type: DataTypes.ENUM(...USER_NAME_PREFIX_VALUES),
        allowNull: true,
      },
      firstName: {
        type: DataTypes.TEXT,
      },
      lastName: {
        type: DataTypes.TEXT,
      },
      phoneNumber: {
        type: DataTypes.TEXT,
      },
      email: {
        type: DataTypes.TEXT,
        allowNull: false,
      },
      disabled: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: false,
      },
      password: {
        type: DataTypes.TEXT,
      },
      emailVerified: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: false,
      },
      emailVerificationToken: {
        type: DataTypes.TEXT,
      },
      emailVerificationTokenExpiresAt: {
        type: DataTypes.DATE,
      },
      passwordResetToken: {
        type: DataTypes.TEXT,
      },
      passwordResetTokenExpiresAt: {
        type: DataTypes.DATE,
      },
      provider: {
        type: DataTypes.TEXT,
      },
      importHash: {
        type: DataTypes.STRING(255),
        allowNull: true,
        unique: true,
      },
      organizationId: { type: DataTypes.UUID, allowNull: true },
      campusId: { type: DataTypes.UUID, allowNull: true },
      createdById: { type: DataTypes.UUID, allowNull: true },
      updatedById: { type: DataTypes.UUID, allowNull: true },
      createdAt: { type: DataTypes.DATE },
      updatedAt: { type: DataTypes.DATE },
      deletedAt: { type: DataTypes.DATE },
    },
    {
      sequelize,
      modelName: 'users',
      timestamps: true,
      paranoid: true,
      freezeTableName: true,
    },
  );

  const providerValues: string[] = Object.values(providers);

  Users.beforeCreate((user: Users) => {
    trimStringFields(user);

    if (
      user.provider &&
      user.provider !== providers.LOCAL &&
      providerValues.includes(user.provider)
    ) {
      user.emailVerified = true;

      if (!user.password) {
        const password = crypto.randomBytes(20).toString('hex');

        user.password = bcrypt.hashSync(password, config.bcrypt.saltRounds);
      }
    }
  });

  Users.beforeUpdate((user: Users) => {
    trimStringFields(user);
  });

  return Users;
}
