import crypto from 'crypto';
import {
  Op,
  type Includeable,
  type InferAttributes,
  type InferCreationAttributes,
  type WhereAttributeHash,
} from 'sequelize';
import db from '@/db/models';
import {
  removeRecord,
  deleteRecordsByIds,
  autocompleteByField,
} from '@/db/api/shared/repository';
import { BULK_IMPORT_TIMESTAMP_STEP_MS } from '@/shared/constants/database';
import { resolvePagination } from '@/shared/constants/pagination';
import {
  EMAIL_ACTION_TOKEN_BYTES,
  EMAIL_ACTION_TOKEN_TTL_MS,
} from '@/shared/constants/auth';
import Utils from '@/db/utils';
import config from '@/shared/config';
import FileDBApi from '@/db/api/file';
import ValidationError from '@/shared/errors/validation';
import type { Users } from '@/db/models/users';
import type {
  AuthenticatedUser,
  CurrentUser,
  DbApiOptions,
  FileInput,
  UserProfileRecord,
} from '@/db/api/types';

type UsersInputData = Partial<InferCreationAttributes<Users>> & {
  app_role?: string | null;
  organizations?: string | null;
  custom_permissions?: string[];
  avatar?: FileInput | FileInput[] | null;
};

interface CreateFromAuthData {
  email: string;
  firstName?: string | null;
  password?: string | null;
  organizationId?: string | null;
}

type DateRange = Array<string | null | undefined>;

interface UsersFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  firstName?: string;
  lastName?: string;
  phoneNumber?: string;
  email?: string;
  password?: string;
  emailVerificationToken?: string;
  passwordResetToken?: string;
  provider?: string;
  emailVerificationTokenExpiresAtRange?: DateRange;
  passwordResetTokenExpiresAtRange?: DateRange;
  active?: boolean | string;
  disabled?: boolean | string;
  emailVerified?: boolean | string;
  app_role?: string;
  organizations?: string;
  custom_permissions?: string;
  createdAtRange?: DateRange;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

function usersTableName(): string {
  const name = db.users.getTableName();
  return typeof name === 'string' ? name : name.tableName;
}

/** Email is a user's login and primary contact, so it is always required. */
function requireEmail(email: string | null | undefined): string {
  if (!email) {
    throw new ValidationError('iam.errors.emailRequired');
  }
  return email;
}

class UsersDBApi {
  static async create(
    payload: { data: UsersInputData },
    _globalAccess: boolean,
    options?: DbApiOptions,
  ): Promise<Users> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;
    const data = payload.data;

    const users = await db.users.create(
      {
        id: data.id || undefined,
        name_prefix: data.name_prefix || null,
        firstName: data.firstName || null,
        lastName: data.lastName || null,
        phoneNumber: data.phoneNumber || null,
        email: requireEmail(data.email),
        disabled: data.disabled || false,
        password: data.password || null,
        emailVerified: data.emailVerified || true,
        emailVerificationToken: data.emailVerificationToken || null,
        emailVerificationTokenExpiresAt:
          data.emailVerificationTokenExpiresAt || null,
        passwordResetToken: data.passwordResetToken || null,
        passwordResetTokenExpiresAt: data.passwordResetTokenExpiresAt || null,
        provider: data.provider || null,
        importHash: data.importHash || null,
        campusId: data.campusId || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    // Roles are assigned explicitly by the provisioning flow; a user created
    // without one has no role and falls back to `guest` until assigned.
    if (data.app_role) {
      await users.setApp_role(data.app_role, { transaction });
    }

    await users.setOrganizations(data.organizations ?? undefined, {
      transaction,
    });
    await users.setCustom_permissions(data.custom_permissions || [], {
      transaction,
    });

    await FileDBApi.replaceRelationFiles(
      {
        belongsTo: usersTableName(),
        belongsToColumn: 'avatar',
        belongsToId: users.id,
      },
      data.avatar,
      options,
    );

    return users;
  }

  static async bulkImport(
    data: UsersInputData[],
    options?: DbApiOptions,
  ): Promise<Users[]> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const usersData = data.map((item, index) => ({
      id: item.id || undefined,
      name_prefix: item.name_prefix || null,
      firstName: item.firstName || null,
      lastName: item.lastName || null,
      phoneNumber: item.phoneNumber || null,
      email: requireEmail(item.email),
      disabled: item.disabled || false,
      password: item.password || null,
      emailVerified: item.emailVerified || false,
      emailVerificationToken: item.emailVerificationToken || null,
      emailVerificationTokenExpiresAt:
        item.emailVerificationTokenExpiresAt || null,
      passwordResetToken: item.passwordResetToken || null,
      passwordResetTokenExpiresAt: item.passwordResetTokenExpiresAt || null,
      provider: item.provider || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * BULK_IMPORT_TIMESTAMP_STEP_MS),
    }));

    const users = await db.users.bulkCreate(usersData, { transaction });

    for (let i = 0; i < users.length; i++) {
      await FileDBApi.replaceRelationFiles(
        {
          belongsTo: usersTableName(),
          belongsToColumn: 'avatar',
          belongsToId: users[i].id,
        },
        data[i].avatar,
        options,
      );
    }

    return users;
  }

  static async update(
    id: string,
    data: UsersInputData,
    _globalAccess: boolean,
    options?: DbApiOptions,
  ): Promise<Users | null> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const users = await db.users.findByPk(id, { transaction });

    if (!users) {
      return null;
    }

    const updatePayload: Partial<InferAttributes<Users>> = {};

    if (data.name_prefix !== undefined)
      updatePayload.name_prefix = data.name_prefix;
    if (data.firstName !== undefined) updatePayload.firstName = data.firstName;
    if (data.lastName !== undefined) updatePayload.lastName = data.lastName;
    if (data.phoneNumber !== undefined)
      updatePayload.phoneNumber = data.phoneNumber;
    if (data.email !== undefined) updatePayload.email = data.email;
    if (data.disabled !== undefined) updatePayload.disabled = data.disabled;
    if (data.password !== undefined) updatePayload.password = data.password;
    if (data.emailVerified !== undefined)
      updatePayload.emailVerified = data.emailVerified;
    if (data.emailVerificationToken !== undefined)
      updatePayload.emailVerificationToken = data.emailVerificationToken;
    if (data.emailVerificationTokenExpiresAt !== undefined)
      updatePayload.emailVerificationTokenExpiresAt =
        data.emailVerificationTokenExpiresAt;
    if (data.passwordResetToken !== undefined)
      updatePayload.passwordResetToken = data.passwordResetToken;
    if (data.passwordResetTokenExpiresAt !== undefined)
      updatePayload.passwordResetTokenExpiresAt =
        data.passwordResetTokenExpiresAt;
    if (data.provider !== undefined) updatePayload.provider = data.provider;
    if (data.campusId !== undefined) updatePayload.campusId = data.campusId;

    updatePayload.updatedById = currentUser.id;

    await users.update(updatePayload, { transaction });

    if (data.app_role !== undefined) {
      await users.setApp_role(data.app_role ?? undefined, { transaction });
    }
    if (data.organizations !== undefined) {
      await users.setOrganizations(data.organizations ?? undefined, {
        transaction,
      });
    }
    if (data.custom_permissions !== undefined) {
      await users.setCustom_permissions(data.custom_permissions, {
        transaction,
      });
    }

    await FileDBApi.replaceRelationFiles(
      {
        belongsTo: usersTableName(),
        belongsToColumn: 'avatar',
        belongsToId: users.id,
      },
      data.avatar,
      options,
    );

    return users;
  }

  static async deleteByIds(
    ids: string[],
    options?: DbApiOptions,
  ): Promise<Users[]> {
    return deleteRecordsByIds(db.users, ids, options);
  }

  static async remove(
    id: string,
    options?: DbApiOptions,
  ): Promise<Users | null> {
    return removeRecord(db.users, id, options);
  }

  static async findBy(
    where: WhereAttributeHash,
    options?: DbApiOptions,
  ): Promise<AuthenticatedUser | null> {
    const transaction = options?.transaction;

    // Per-request auth/session load. Authorization needs only role (+its
    // permissions), per-user permissions, staff profile, and org — loaded in a
    // single eager query (no per-association getter round-trips). `app_role`
    // carries its `permissions`, so the permission middleware reads them off
    // the loaded array instead of issuing another `getPermissions()` query.
    // `messages_sent_by` (unbounded) and `avatar` are intentionally skipped.
    const users = await db.users.findOne({
      where,
      include: [
        {
          model: db.roles,
          as: 'app_role',
          include: [
            {
              model: db.permissions,
              as: 'permissions',
              through: { attributes: [] },
            },
          ],
        },
        { model: db.staff, as: 'staff_user' },
        {
          model: db.permissions,
          as: 'custom_permissions',
          through: { attributes: [] },
        },
        { model: db.organizations, as: 'organizations' },
      ],
      transaction,
    });

    if (!users) {
      return null;
    }

    return {
      ...users.get({ plain: true }),
      staff_user: users.staff_user ?? [],
      app_role: users.app_role ?? null,
      app_role_permissions: users.app_role?.permissions ?? [],
      custom_permissions: users.custom_permissions ?? [],
      organizations: users.organizations ?? null,
    };
  }

  /**
   * Trimmed profile fetch for `GET /me` (and the signin/refresh responses):
   * one eager-loaded query selecting only the columns and relations the
   * profile DTO reads — no per-association getter round-trips, no `getCampus`.
   */
  static async findProfileById(
    id: string,
    options?: DbApiOptions,
  ): Promise<UserProfileRecord | null> {
    const transaction = options?.transaction;

    const user = await db.users.findByPk(id, {
      // `app_roleId`/`organizationId` are the belongsTo foreign keys needed to
      // join `app_role`/`organizations`; they are not returned in the DTO.
      attributes: [
        'id',
        'email',
        'firstName',
        'lastName',
        'organizationId',
        'app_roleId',
      ],
      include: [
        {
          model: db.roles,
          as: 'app_role',
          attributes: ['id', 'name', 'globalAccess'],
          include: [
            {
              model: db.permissions,
              as: 'permissions',
              attributes: ['id', 'name'],
              through: { attributes: [] },
            },
          ],
        },
        {
          model: db.permissions,
          as: 'custom_permissions',
          attributes: ['id', 'name'],
          through: { attributes: [] },
        },
        {
          model: db.organizations,
          as: 'organizations',
          attributes: ['id', 'name'],
        },
        {
          model: db.staff,
          as: 'staff_user',
          attributes: [
            'id',
            'employee_number',
            'job_title',
            'staff_type',
            'status',
            'organizationId',
            'campusId',
            'userId',
          ],
          include: [
            {
              model: db.campuses,
              as: 'campus',
              attributes: ['id', 'name', 'code'],
            },
          ],
        },
      ],
      transaction,
    });

    if (!user) {
      return null;
    }

    const staffProfile = user.staff_user?.[0] ?? null;

    return {
      id: user.id,
      email: user.email,
      name_prefix: user.name_prefix ?? null,
      firstName: user.firstName,
      lastName: user.lastName,
      organizationId: user.organizationId,
      organizations: user.organizations ?? null,
      app_role: user.app_role ?? null,
      app_role_permissions: user.app_role?.permissions ?? [],
      custom_permissions: user.custom_permissions ?? [],
      staff_user: user.staff_user ?? [],
      staff_campus: staffProfile?.campus ?? null,
    };
  }

  static async findAll(
    filter: UsersFilter,
    globalAccess: boolean,
    options?: DbApiOptions,
  ): Promise<{ rows: Users[]; count: number }> {
    const { limit, offset } = resolvePagination(filter.limit, filter.page);

    let where: WhereAttributeHash = {};

    const userOrganizations = options?.currentUser?.organizations?.id ?? null;
    if (userOrganizations && options?.currentUser?.organizationId) {
      where.organizationId = options.currentUser.organizationId;
    }

    let include: Includeable[] = [
      {
        model: db.roles,
        as: 'app_role',
        where: filter.app_role
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.app_role
                      .split('|')
                      .map((t) => Utils.uuid(t)),
                  },
                },
                {
                  name: {
                    [Op.or]: filter.app_role
                      .split('|')
                      .map((t) => ({ [Op.iLike]: `%${t}%` })),
                  },
                },
              ],
            }
          : {},
      },
      { model: db.organizations, as: 'organizations' },
      { model: db.permissions, as: 'custom_permissions', required: false },
      { model: db.file, as: 'avatar' },
    ];

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.firstName) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('users', 'firstName', filter.firstName),
      };
    }
    if (filter.lastName) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('users', 'lastName', filter.lastName),
      };
    }
    if (filter.phoneNumber) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('users', 'phoneNumber', filter.phoneNumber),
      };
    }
    if (filter.email) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('users', 'email', filter.email),
      };
    }
    if (filter.password) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('users', 'password', filter.password),
      };
    }
    if (filter.emailVerificationToken) {
      where = {
        ...where,
        [Op.and]: Utils.ilike(
          'users',
          'emailVerificationToken',
          filter.emailVerificationToken,
        ),
      };
    }
    if (filter.passwordResetToken) {
      where = {
        ...where,
        [Op.and]: Utils.ilike(
          'users',
          'passwordResetToken',
          filter.passwordResetToken,
        ),
      };
    }
    if (filter.provider) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('users', 'provider', filter.provider),
      };
    }
    if (filter.emailVerificationTokenExpiresAtRange) {
      const [start, end] = filter.emailVerificationTokenExpiresAtRange;
      if (start !== undefined && start !== null && start !== '') {
        where = {
          ...where,
          emailVerificationTokenExpiresAt: { [Op.gte]: start },
        };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          emailVerificationTokenExpiresAt: {
            ...(typeof where.emailVerificationTokenExpiresAt === 'object'
              ? where.emailVerificationTokenExpiresAt
              : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.passwordResetTokenExpiresAtRange) {
      const [start, end] = filter.passwordResetTokenExpiresAtRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, passwordResetTokenExpiresAt: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          passwordResetTokenExpiresAt: {
            ...(typeof where.passwordResetTokenExpiresAt === 'object'
              ? where.passwordResetTokenExpiresAt
              : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    if (filter.disabled) {
      where = { ...where, disabled: filter.disabled };
    }
    if (filter.emailVerified) {
      where = { ...where, emailVerified: filter.emailVerified };
    }
    if (filter.organizations) {
      const listItems = filter.organizations
        .split('|')
        .map((item) => Utils.uuid(item));
      where = { ...where, organizationId: { [Op.or]: listItems } };
    }
    if (filter.custom_permissions) {
      const searchTerms = filter.custom_permissions.split('|');
      include = [
        {
          model: db.permissions,
          as: 'custom_permissions_filter',
          required: searchTerms.length > 0,
          where:
            searchTerms.length > 0
              ? {
                  [Op.or]: [
                    { id: { [Op.in]: searchTerms.map((t) => Utils.uuid(t)) } },
                    {
                      name: {
                        [Op.or]: searchTerms.map((t) => ({
                          [Op.iLike]: `%${t}%`,
                        })),
                      },
                    },
                  ],
                }
              : undefined,
        },
        ...include,
      ];
    }
    if (filter.createdAtRange) {
      const [start, end] = filter.createdAtRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, createdAt: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          createdAt: {
            ...(typeof where.createdAt === 'object' ? where.createdAt : {}),
            [Op.lte]: end,
          },
        };
      }
    }

    if (globalAccess) {
      delete where.organizationId;
    }

    const order: [string, string][] =
      filter.field && filter.sort
        ? [[filter.field, filter.sort]]
        : [['createdAt', 'desc']];

    const { rows, count } = await db.users.findAndCountAll({
      where,
      include,
      distinct: true,
      order,
      transaction: options?.transaction,
      limit: !options?.countOnly && limit ? limit : undefined,
      offset: !options?.countOnly && offset ? offset : undefined,
    });

    return { rows: options?.countOnly ? [] : rows, count };
  }

  static async findAllAutocomplete(
    query: string | undefined,
    limit: number | undefined,
    offset: number | undefined,
    globalAccess: boolean,
    organizationId: string | undefined,
  ): Promise<Array<{ id: string; label: string | null }>> {
    return autocompleteByField(
      db.users,
      'name',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }

  static async createFromAuth(
    data: CreateFromAuthData,
    options?: DbApiOptions,
  ): Promise<Users> {
    const transaction = options?.transaction;

    const users = await db.users.create(
      {
        email: data.email,
        firstName: data.firstName,
        password: data.password,
        organizationId: data.organizationId,
      },
      { transaction },
    );

    const app_role = await db.roles.findOne({
      where: { name: config.roles.user || 'User' },
    });
    if (app_role?.id) {
      await users.setApp_role(app_role.id, { transaction });
    }

    return users;
  }

  static async updatePassword(
    id: string,
    password: string,
    options?: DbApiOptions,
  ): Promise<Users | null> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const users = await db.users.findByPk(id, { transaction });

    if (!users) {
      return null;
    }

    await users.update(
      { password, updatedById: currentUser.id },
      { transaction },
    );

    return users;
  }

  static async generateEmailVerificationToken(
    email: string,
    options?: DbApiOptions,
  ): Promise<string> {
    return this._generateToken('emailVerification', email, options);
  }

  static async generatePasswordResetToken(
    email: string,
    options?: DbApiOptions,
  ): Promise<string> {
    return this._generateToken('passwordReset', email, options);
  }

  static async findByPasswordResetToken(
    token: string,
    options?: DbApiOptions,
  ): Promise<Users | null> {
    const transaction = options?.transaction;

    return db.users.findOne({
      where: {
        passwordResetToken: token,
        passwordResetTokenExpiresAt: { [Op.gt]: new Date() },
      },
      transaction,
    });
  }

  static async findByEmailVerificationToken(
    token: string,
    options?: DbApiOptions,
  ): Promise<Users | null> {
    const transaction = options?.transaction;

    return db.users.findOne({
      where: {
        emailVerificationToken: token,
        emailVerificationTokenExpiresAt: { [Op.gt]: new Date() },
      },
      transaction,
    });
  }

  static async markEmailVerified(
    id: string,
    options?: DbApiOptions,
  ): Promise<boolean> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const users = await db.users.findByPk(id, { transaction });

    if (!users) {
      return false;
    }

    await users.update(
      { emailVerified: true, updatedById: currentUser.id },
      { transaction },
    );

    return true;
  }

  private static async _generateToken(
    kind: 'emailVerification' | 'passwordReset',
    email: string,
    options?: DbApiOptions,
  ): Promise<string> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const users = await db.users.findOne({
      where: { email: email.toLowerCase() },
      transaction,
    });

    const token = crypto.randomBytes(EMAIL_ACTION_TOKEN_BYTES).toString('hex');
    const tokenExpiresAt = new Date(Date.now() + EMAIL_ACTION_TOKEN_TTL_MS);

    if (users) {
      const payload: Partial<InferAttributes<Users>> = {
        updatedById: currentUser.id,
      };
      if (kind === 'emailVerification') {
        payload.emailVerificationToken = token;
        payload.emailVerificationTokenExpiresAt = tokenExpiresAt;
      } else {
        payload.passwordResetToken = token;
        payload.passwordResetTokenExpiresAt = tokenExpiresAt;
      }
      await users.update(payload, { transaction });
    }

    return token;
  }
}

export default UsersDBApi;
