import {
  Op,
  type InferAttributes,
  type InferCreationAttributes,
  type WhereAttributeHash,
} from 'sequelize';
import db from '@/db/models';
import {
  removeRecord,
  deleteRecordsByIds,
  autocompleteByField,
  findOwnedByPk,
  tenantWhere,
} 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 ValidationError from '@/shared/errors/validation';
import type { Campuses } from '@/db/models/campuses';
import type { CurrentUser, DbApiOptions } from '@/db/api/types';

type CampusesData = Partial<InferCreationAttributes<Campuses>> & {
  organization?: string | null;
};

interface CampusesFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  name?: string;
  code?: string;
  address?: string;
  phone?: string;
  email?: string;
  active?: boolean | string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

class CampusesDBApi {
  static async create(
    data: CampusesData,
    options?: DbApiOptions,
  ): Promise<Campuses> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    if (data.name == null || data.code == null) {
      throw new ValidationError();
    }

    const campuses = await db.campuses.create(
      {
        id: data.id || undefined,
        name: data.name,
        code: data.code,
        address: data.address || null,
        phone: data.phone || null,
        email: data.email || null,
        mascot: data.mascot || null,
        color: data.color || null,
        bgGradient: data.bgGradient || null,
        borderColor: data.borderColor || null,
        textColor: data.textColor || null,
        bgLight: data.bgLight || null,
        description: data.description || null,
        isOnline: data.isOnline || false,
        active: data.active || false,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await campuses.setOrganization(currentUser.organizationId ?? undefined, {
      transaction,
    });

    return campuses;
  }

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

    const campusesData = data.map((item, index) => {
      if (item.name == null || item.code == null) {
        throw new ValidationError();
      }
      return {
      id: item.id || undefined,
      name: item.name,
      code: item.code,
      address: item.address || null,
      phone: item.phone || null,
      email: item.email || null,
      mascot: item.mascot || null,
      color: item.color || null,
      bgGradient: item.bgGradient || null,
      borderColor: item.borderColor || null,
      textColor: item.textColor || null,
      bgLight: item.bgLight || null,
      description: item.description || null,
      isOnline: item.isOnline || false,
      active: item.active || false,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * BULK_IMPORT_TIMESTAMP_STEP_MS),
      };
    });

    return db.campuses.bulkCreate(campusesData, { transaction });
  }

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

    const campuses = await findOwnedByPk(db.campuses, id, options);

    if (!campuses) {
      return null;
    }

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

    if (data.name !== undefined) updatePayload.name = data.name;
    if (data.code !== undefined) updatePayload.code = data.code;
    if (data.address !== undefined) updatePayload.address = data.address;
    if (data.phone !== undefined) updatePayload.phone = data.phone;
    if (data.email !== undefined) updatePayload.email = data.email;
    if (data.mascot !== undefined) updatePayload.mascot = data.mascot;
    if (data.color !== undefined) updatePayload.color = data.color;
    if (data.bgGradient !== undefined) updatePayload.bgGradient = data.bgGradient;
    if (data.borderColor !== undefined)
      updatePayload.borderColor = data.borderColor;
    if (data.textColor !== undefined) updatePayload.textColor = data.textColor;
    if (data.bgLight !== undefined) updatePayload.bgLight = data.bgLight;
    if (data.description !== undefined)
      updatePayload.description = data.description;
    if (data.isOnline !== undefined) updatePayload.isOnline = data.isOnline;
    if (data.active !== undefined) updatePayload.active = data.active;

    updatePayload.updatedById = currentUser.id;

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

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

    return campuses;
  }

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

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

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

    const campuses = await db.campuses.findOne({
      where: { ...where, ...tenantWhere(options?.currentUser) },
      transaction,
    });

    if (!campuses) {
      return null;
    }

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

    const [
      staff_campus,
      classes_campus,
      timetables_campus,
      attendance_sessions_campus,
      messages_campus,
      organization,
    ] = await Promise.all([
      campuses.getStaff_campus({ transaction }),
      campuses.getClasses_campus({ transaction }),
      campuses.getTimetables_campus({ transaction }),
      campuses.getAttendance_sessions_campus({ transaction }),
      campuses.getMessages_campus({ transaction }),
      campuses.getOrganization({ transaction }),
    ]);
    output.staff_campus = staff_campus;
    output.classes_campus = classes_campus;
    output.timetables_campus = timetables_campus;
    output.attendance_sessions_campus = attendance_sessions_campus;
    output.messages_campus = messages_campus;
    output.organization = organization;

    return output;
  }

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

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.name) {
      where = { ...where, [Op.and]: Utils.ilike('campuses', 'name', filter.name) };
    }
    if (filter.code) {
      where = { ...where, [Op.and]: Utils.ilike('campuses', 'code', filter.code) };
    }
    if (filter.address) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('campuses', 'address', filter.address),
      };
    }
    if (filter.phone) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('campuses', 'phone', filter.phone),
      };
    }
    if (filter.email) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('campuses', 'email', filter.email),
      };
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    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.campuses.findAndCountAll({
      where,
      include: [{ model: db.organizations, as: 'organization' }],
      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.campuses,
      'name',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default CampusesDBApi;
