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

type FeePlansData = Partial<InferCreationAttributes<FeePlans>> & {
  organization?: string | null;
  academic_year?: string | null;
  grade?: string | null;
};

interface FeePlansFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  name?: string;
  notes?: string;
  total_amountRange?: Array<number | string | null | undefined>;
  active?: boolean | string;
  billing_cycle?: string;
  academic_year?: string;
  grade?: string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

class Fee_plansDBApi {
  static async create(
    data: FeePlansData,
    options?: DbApiOptions,
  ): Promise<FeePlans> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const fee_plans = await db.fee_plans.create(
      {
        id: data.id || undefined,
        name: data.name || null,
        billing_cycle: data.billing_cycle || null,
        total_amount: data.total_amount || null,
        active: data.active || false,
        notes: data.notes || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await fee_plans.setOrganization(currentUser.organizationId ?? undefined, {
      transaction,
    });
    await fee_plans.setAcademic_year(data.academic_year ?? undefined, {
      transaction,
    });
    await fee_plans.setGrade(data.grade ?? undefined, { transaction });

    return fee_plans;
  }

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

    const fee_plansData = data.map((item, index) => ({
      id: item.id || undefined,
      name: item.name || null,
      billing_cycle: item.billing_cycle || null,
      total_amount: item.total_amount || null,
      active: item.active || false,
      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),
    }));

    return db.fee_plans.bulkCreate(fee_plansData, { transaction });
  }

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

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

    if (!fee_plans) {
      return null;
    }

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

    if (data.name !== undefined) updatePayload.name = data.name;
    if (data.billing_cycle !== undefined)
      updatePayload.billing_cycle = data.billing_cycle;
    if (data.total_amount !== undefined)
      updatePayload.total_amount = data.total_amount;
    if (data.active !== undefined) updatePayload.active = data.active;
    if (data.notes !== undefined) updatePayload.notes = data.notes;

    updatePayload.updatedById = currentUser.id;

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

    if (data.organization !== undefined) {
      const orgId = globalAccess
        ? data.organization
        : currentUser.organizationId;
      await fee_plans.setOrganization(orgId ?? undefined, { transaction });
    }
    if (data.academic_year !== undefined) {
      await fee_plans.setAcademic_year(data.academic_year ?? undefined, {
        transaction,
      });
    }
    if (data.grade !== undefined) {
      await fee_plans.setGrade(data.grade ?? undefined, { transaction });
    }

    return fee_plans;
  }

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

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

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

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

    if (!fee_plans) {
      return null;
    }

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

    const [invoices_fee_plan, organization, academic_year, grade] =
      await Promise.all([
        fee_plans.getInvoices_fee_plan({ transaction }),
        fee_plans.getOrganization({ transaction }),
        fee_plans.getAcademic_year({ transaction }),
        fee_plans.getGrade({ transaction }),
      ]);
    output.invoices_fee_plan = invoices_fee_plan;
    output.organization = organization;
    output.academic_year = academic_year;
    output.grade = grade;

    return output;
  }

  static async findAll(
    filter: FeePlansFilter,
    globalAccess: boolean,
    options?: DbApiOptions,
  ): Promise<{ rows: FeePlans[]; 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.academic_years,
        as: 'academic_year',
        where: filter.academic_year
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.academic_year
                      .split('|')
                      .map((t) => Utils.uuid(t)),
                  },
                },
                {
                  name: {
                    [Op.or]: filter.academic_year
                      .split('|')
                      .map((t) => ({ [Op.iLike]: `%${t}%` })),
                  },
                },
              ],
            }
          : {},
      },
      {
        model: db.grades,
        as: 'grade',
        where: filter.grade
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.grade.split('|').map((t) => Utils.uuid(t)),
                  },
                },
                {
                  name: {
                    [Op.or]: filter.grade
                      .split('|')
                      .map((t) => ({ [Op.iLike]: `%${t}%` })),
                  },
                },
              ],
            }
          : {},
      },
    ];

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.name) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('fee_plans', 'name', filter.name),
      };
    }
    if (filter.notes) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('fee_plans', 'notes', filter.notes),
      };
    }
    if (filter.total_amountRange) {
      const [start, end] = filter.total_amountRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, total_amount: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          total_amount: {
            ...(typeof where.total_amount === 'object'
              ? where.total_amount
              : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    if (filter.billing_cycle) {
      where = { ...where, billing_cycle: filter.billing_cycle };
    }
    if (filter.active) {
      where = { ...where, active: filter.active };
    }
    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.fee_plans.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.fee_plans,
      'name',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default Fee_plansDBApi;
