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

type GuardiansData = Partial<InferCreationAttributes<Guardians>> & {
  organization?: string | null;
  student?: string | null;
};

interface GuardiansFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  full_name?: string;
  phone?: string;
  email?: string;
  address?: string;
  active?: boolean | string;
  relationship?: string;
  primary_contact?: boolean | string;
  student?: string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

class GuardiansDBApi {
  static async create(
    data: GuardiansData,
    options?: DbApiOptions,
  ): Promise<Guardians> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const guardians = await db.guardians.create(
      {
        id: data.id || undefined,
        full_name: data.full_name || null,
        relationship: data.relationship || null,
        phone: data.phone || null,
        email: data.email || null,
        address: data.address || null,
        primary_contact: data.primary_contact || false,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await guardians.setOrganization(currentUser.organizationId ?? undefined, {
      transaction,
    });
    await guardians.setStudent(data.student ?? undefined, { transaction });

    return guardians;
  }

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

    const guardiansData = data.map((item, index) => ({
      id: item.id || undefined,
      full_name: item.full_name || null,
      relationship: item.relationship || null,
      phone: item.phone || null,
      email: item.email || null,
      address: item.address || null,
      primary_contact: item.primary_contact || false,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * BULK_IMPORT_TIMESTAMP_STEP_MS),
    }));

    return db.guardians.bulkCreate(guardiansData, { transaction });
  }

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

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

    if (!guardians) {
      return null;
    }

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

    if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
    if (data.relationship !== undefined)
      updatePayload.relationship = data.relationship;
    if (data.phone !== undefined) updatePayload.phone = data.phone;
    if (data.email !== undefined) updatePayload.email = data.email;
    if (data.address !== undefined) updatePayload.address = data.address;
    if (data.primary_contact !== undefined)
      updatePayload.primary_contact = data.primary_contact;

    updatePayload.updatedById = currentUser.id;

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

    if (data.organization !== undefined) {
      const orgId = globalAccess
        ? data.organization
        : currentUser.organizationId;
      await guardians.setOrganization(orgId ?? undefined, { transaction });
    }
    if (data.student !== undefined) {
      await guardians.setStudent(data.student ?? undefined, { transaction });
    }

    return guardians;
  }

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

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

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

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

    if (!guardians) {
      return null;
    }

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

    const [organization, student] = await Promise.all([
      guardians.getOrganization({ transaction }),
      guardians.getStudent({ transaction }),
    ]);
    output.organization = organization;
    output.student = student;

    return output;
  }

  static async findAll(
    filter: GuardiansFilter,
    globalAccess: boolean,
    options?: DbApiOptions,
  ): Promise<{ rows: Guardians[]; 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.students,
        as: 'student',
        where: filter.student
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.student.split('|').map((t) => Utils.uuid(t)),
                  },
                },
                {
                  student_number: {
                    [Op.or]: filter.student
                      .split('|')
                      .map((t) => ({ [Op.iLike]: `%${t}%` })),
                  },
                },
              ],
            }
          : {},
      },
    ];

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.full_name) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('guardians', 'full_name', filter.full_name),
      };
    }
    if (filter.phone) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('guardians', 'phone', filter.phone),
      };
    }
    if (filter.email) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('guardians', 'email', filter.email),
      };
    }
    if (filter.address) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('guardians', 'address', filter.address),
      };
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    if (filter.relationship) {
      where = { ...where, relationship: filter.relationship };
    }
    if (filter.primary_contact) {
      where = { ...where, primary_contact: filter.primary_contact };
    }
    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.guardians.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.guardians,
      'full_name',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default GuardiansDBApi;
