import {
  Op,
  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 type { Permissions } from '@/db/models/permissions';
import type { CurrentUser, DbApiOptions } from '@/db/api/types';

type PermissionsData = Partial<InferCreationAttributes<Permissions>>;

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

const NO_USER: CurrentUser = { id: null };

class PermissionsDBApi {
  static async create(
    data: PermissionsData,
    options?: DbApiOptions,
  ): Promise<Permissions> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    return db.permissions.create(
      {
        id: data.id || undefined,
        name: data.name || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );
  }

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

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

    return db.permissions.bulkCreate(permissionsData, { transaction });
  }

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

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

    if (!permissions) {
      return null;
    }

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

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

    updatePayload.updatedById = currentUser.id;

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

    return permissions;
  }

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

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

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

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

    if (!permissions) {
      return null;
    }

    return permissions.get({ plain: true });
  }

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

    let where: WhereAttributeHash = {};

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.name) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('permissions', 'name', filter.name),
      };
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    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,
          },
        };
      }
    }

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

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

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

    const records = await db.permissions.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 PermissionsDBApi;
