import {
  Op,
  type Includeable,
  type InferAttributes,
  type InferCreationAttributes,
  type WhereAttributeHash,
} from 'sequelize';
import db from '@/db/models';
import {
  removeRecord,
  deleteRecordsByIds,
} from '@/db/api/shared/repository';
import { BULK_IMPORT_TIMESTAMP_STEP_MS } from '@/shared/constants/database';
import { resolvePagination } from '@/shared/constants/pagination';
import Utils from '@/db/utils';
import config from '@/shared/config';
import type { Roles } from '@/db/models/roles';
import type { CurrentUser, DbApiOptions } from '@/db/api/types';

type RolesData = Partial<InferCreationAttributes<Roles>> & {
  permissions?: string[];
};

interface RolesFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  name?: string;
  active?: boolean | string;
  globalAccess?: boolean | string;
  permissions?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

class RolesDBApi {
  static async create(
    data: RolesData,
    options?: DbApiOptions,
  ): Promise<Roles> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const roles = await db.roles.create(
      {
        id: data.id || undefined,
        name: data.name || null,
        scope: data.scope,
        globalAccess: data.globalAccess || false,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await roles.setPermissions(data.permissions || [], { transaction });

    return roles;
  }

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

    const rolesData = data.map((item, index) => ({
      id: item.id || undefined,
      name: item.name || null,
      scope: item.scope,
      globalAccess: item.globalAccess || false,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * BULK_IMPORT_TIMESTAMP_STEP_MS),
    }));

    return db.roles.bulkCreate(rolesData, { transaction });
  }

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

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

    if (!roles) {
      return null;
    }

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

    if (data.name !== undefined) updatePayload.name = data.name;
    if (data.scope !== undefined) updatePayload.scope = data.scope;
    if (data.globalAccess !== undefined)
      updatePayload.globalAccess = data.globalAccess;

    updatePayload.updatedById = currentUser.id;

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

    if (data.permissions !== undefined) {
      await roles.setPermissions(data.permissions, { transaction });
    }

    return roles;
  }

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

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

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

    const roles = await db.roles.findOne({ where, transaction });

    if (!roles) {
      return null;
    }

    const output: Record<string, unknown> = roles.get({ plain: true });

    const [users_app_role, permissions] = await Promise.all([
      roles.getUsers_app_role({ transaction }),
      roles.getPermissions({ transaction }),
    ]);
    output.users_app_role = users_app_role;
    output.permissions = permissions;

    return output;
  }

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

    let where: WhereAttributeHash = {};
    let include: Includeable[] = [
      { model: db.permissions, as: 'permissions', required: false },
    ];

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.name) {
      where = { ...where, [Op.and]: Utils.ilike('roles', 'name', filter.name) };
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    if (filter.globalAccess) {
      where = { ...where, globalAccess: filter.globalAccess };
    }
    if (filter.permissions) {
      const searchTerms = filter.permissions.split('|');
      include = [
        {
          model: db.permissions,
          as: 'permissions_filter',
          required: searchTerms.length > 0,
          where:
            searchTerms.length > 0
              ? {
                  [Op.or]: [
                    { id: { [Op.in]: searchTerms.map((term) => Utils.uuid(term)) } },
                    {
                      name: {
                        [Op.or]: searchTerms.map((term) => ({
                          [Op.iLike]: `%${term}%`,
                        })),
                      },
                    },
                  ],
                }
              : 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) {
      where = { name: { [Op.ne]: config.roles.super_admin } };
    }

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

    const { rows, count } = await db.roles.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,
  ): Promise<Array<{ id: string; label: string | null }>> {
    let where: WhereAttributeHash = {};

    if (!globalAccess) {
      where = { name: { [Op.ne]: config.roles.super_admin } };
    }

    if (query) {
      where = {
        [Op.or]: [
          { id: Utils.uuid(query) },
          Utils.ilike('roles', 'name', query),
        ],
      };
    }

    const records = await db.roles.findAll({
      attributes: ['id', 'name'],
      where,
      limit: limit ? Number(limit) : undefined,
      offset: offset ? Number(offset) : undefined,
      order: [['name', 'ASC']],
    });

    return records.map((record) => ({
      id: record.id,
      label: record.name,
    }));
  }
}

export default RolesDBApi;
