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 Utils from '@/db/utils';
import FileDBApi from '@/db/api/file';
import type { Payments } from '@/db/models/payments';
import type { CurrentUser, DbApiOptions, FileInput } from '@/db/api/types';

type PaymentsData = Partial<InferCreationAttributes<Payments>> & {
  organization?: string | null;
  invoice?: string | null;
  received_by?: string | null;
  proof?: FileInput | FileInput[] | null;
};

interface PaymentsFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  receipt_number?: string;
  reference_code?: string;
  notes?: string;
  paid_atRange?: Array<string | null | undefined>;
  amountRange?: Array<number | string | null | undefined>;
  active?: boolean | string;
  method?: string;
  invoice?: string;
  received_by?: string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

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

class PaymentsDBApi {
  static async create(
    data: PaymentsData,
    options?: DbApiOptions,
  ): Promise<Payments> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const payments = await db.payments.create(
      {
        id: data.id || undefined,
        receipt_number: data.receipt_number || null,
        paid_at: data.paid_at || null,
        amount: data.amount || null,
        method: data.method || null,
        reference_code: data.reference_code || null,
        notes: data.notes || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await payments.setOrganization(currentUser.organizationId ?? undefined, {
      transaction,
    });
    await payments.setInvoice(data.invoice ?? undefined, { transaction });
    await payments.setReceived_by(data.received_by ?? undefined, {
      transaction,
    });

    await FileDBApi.replaceRelationFiles(
      {
        belongsTo: paymentsTableName(),
        belongsToColumn: 'proof',
        belongsToId: payments.id,
      },
      data.proof,
      options,
    );

    return payments;
  }

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

    const paymentsData = data.map((item, index) => ({
      id: item.id || undefined,
      receipt_number: item.receipt_number || null,
      paid_at: item.paid_at || null,
      amount: item.amount || null,
      method: item.method || null,
      reference_code: item.reference_code || null,
      notes: item.notes || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * BULK_IMPORT_TIMESTAMP_STEP_MS),
    }));

    const payments = await db.payments.bulkCreate(paymentsData, { transaction });

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

    return payments;
  }

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

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

    if (!payments) {
      return null;
    }

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

    if (data.receipt_number !== undefined)
      updatePayload.receipt_number = data.receipt_number;
    if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
    if (data.amount !== undefined) updatePayload.amount = data.amount;
    if (data.method !== undefined) updatePayload.method = data.method;
    if (data.reference_code !== undefined)
      updatePayload.reference_code = data.reference_code;
    if (data.notes !== undefined) updatePayload.notes = data.notes;

    updatePayload.updatedById = currentUser.id;

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

    if (data.organization !== undefined) {
      const orgId = globalAccess
        ? data.organization
        : currentUser.organizationId;
      await payments.setOrganization(orgId ?? undefined, { transaction });
    }
    if (data.invoice !== undefined) {
      await payments.setInvoice(data.invoice ?? undefined, { transaction });
    }
    if (data.received_by !== undefined) {
      await payments.setReceived_by(data.received_by ?? undefined, {
        transaction,
      });
    }

    await FileDBApi.replaceRelationFiles(
      {
        belongsTo: paymentsTableName(),
        belongsToColumn: 'proof',
        belongsToId: payments.id,
      },
      data.proof,
      options,
    );

    return payments;
  }

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

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

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

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

    if (!payments) {
      return null;
    }

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

    const [organization, invoice, received_by, proof] = await Promise.all([
      payments.getOrganization({ transaction }),
      payments.getInvoice({ transaction }),
      payments.getReceived_by({ transaction }),
      payments.getProof({ transaction }),
    ]);
    output.organization = organization;
    output.invoice = invoice;
    output.received_by = received_by;
    output.proof = proof;

    return output;
  }

  static async findAll(
    filter: PaymentsFilter,
    globalAccess: boolean,
    options?: DbApiOptions,
  ): Promise<{ rows: Payments[]; 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;
    }

    const include: Includeable[] = [
      { model: db.organizations, as: 'organization' },
      {
        model: db.invoices,
        as: 'invoice',
        where: filter.invoice
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.invoice.split('|').map((t) => Utils.uuid(t)),
                  },
                },
                {
                  invoice_number: {
                    [Op.or]: filter.invoice
                      .split('|')
                      .map((t) => ({ [Op.iLike]: `%${t}%` })),
                  },
                },
              ],
            }
          : {},
      },
      {
        model: db.staff,
        as: 'received_by',
        where: filter.received_by
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.received_by
                      .split('|')
                      .map((t) => Utils.uuid(t)),
                  },
                },
                {
                  employee_number: {
                    [Op.or]: filter.received_by
                      .split('|')
                      .map((t) => ({ [Op.iLike]: `%${t}%` })),
                  },
                },
              ],
            }
          : {},
      },
      { model: db.file, as: 'proof' },
    ];

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.receipt_number) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('payments', 'receipt_number', filter.receipt_number),
      };
    }
    if (filter.reference_code) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('payments', 'reference_code', filter.reference_code),
      };
    }
    if (filter.notes) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('payments', 'notes', filter.notes),
      };
    }
    if (filter.paid_atRange) {
      const [start, end] = filter.paid_atRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, paid_at: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          paid_at: {
            ...(typeof where.paid_at === 'object' ? where.paid_at : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.amountRange) {
      const [start, end] = filter.amountRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, amount: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          amount: {
            ...(typeof where.amount === 'object' ? where.amount : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    if (filter.method) {
      where = { ...where, method: filter.method };
    }
    if (filter.organization) {
      const listItems = filter.organization
        .split('|')
        .map((item) => Utils.uuid(item));
      where = { ...where, organizationId: { [Op.or]: listItems } };
    }
    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.payments.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.payments,
      'receipt_number',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default PaymentsDBApi;
