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

type StudentsData = Partial<InferCreationAttributes<Students>> & {
  organization?: string | null;
  campus?: string | null;
  photo?: FileInput | FileInput[] | null;
};

interface StudentsFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  student_number?: string;
  first_name?: string;
  last_name?: string;
  email?: string;
  phone?: string;
  address?: string;
  date_of_birthRange?: Array<string | null | undefined>;
  enrollment_dateRange?: Array<string | null | undefined>;
  active?: boolean | string;
  gender?: string;
  status?: string;
  campus?: string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

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

class StudentsDBApi {
  static async create(
    data: StudentsData,
    options?: DbApiOptions,
  ): Promise<Students> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const students = await db.students.create(
      {
        id: data.id || undefined,
        student_number: data.student_number || null,
        first_name: data.first_name || null,
        last_name: data.last_name || null,
        gender: data.gender || null,
        date_of_birth: data.date_of_birth || null,
        enrollment_date: data.enrollment_date || null,
        status: data.status || null,
        email: data.email || null,
        phone: data.phone || null,
        address: data.address || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await students.setOrganization(currentUser.organizationId ?? undefined, {
      transaction,
    });
    await students.setCampus(data.campus ?? undefined, { transaction });

    await FileDBApi.replaceRelationFiles(
      {
        belongsTo: studentsTableName(),
        belongsToColumn: 'photo',
        belongsToId: students.id,
      },
      data.photo,
      options,
    );

    return students;
  }

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

    const studentsData = data.map((item, index) => ({
      id: item.id || undefined,
      student_number: item.student_number || null,
      first_name: item.first_name || null,
      last_name: item.last_name || null,
      gender: item.gender || null,
      date_of_birth: item.date_of_birth || null,
      enrollment_date: item.enrollment_date || null,
      status: item.status || null,
      email: item.email || null,
      phone: item.phone || null,
      address: item.address || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * BULK_IMPORT_TIMESTAMP_STEP_MS),
    }));

    const students = await db.students.bulkCreate(studentsData, { transaction });

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

    return students;
  }

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

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

    if (!students) {
      return null;
    }

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

    if (data.student_number !== undefined)
      updatePayload.student_number = data.student_number;
    if (data.first_name !== undefined)
      updatePayload.first_name = data.first_name;
    if (data.last_name !== undefined) updatePayload.last_name = data.last_name;
    if (data.gender !== undefined) updatePayload.gender = data.gender;
    if (data.date_of_birth !== undefined)
      updatePayload.date_of_birth = data.date_of_birth;
    if (data.enrollment_date !== undefined)
      updatePayload.enrollment_date = data.enrollment_date;
    if (data.status !== undefined) updatePayload.status = data.status;
    if (data.email !== undefined) updatePayload.email = data.email;
    if (data.phone !== undefined) updatePayload.phone = data.phone;
    if (data.address !== undefined) updatePayload.address = data.address;

    updatePayload.updatedById = currentUser.id;

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

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

    await FileDBApi.replaceRelationFiles(
      {
        belongsTo: studentsTableName(),
        belongsToColumn: 'photo',
        belongsToId: students.id,
      },
      data.photo,
      options,
    );

    return students;
  }

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

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

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

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

    if (!students) {
      return null;
    }

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

    const [
      guardians_student,
      class_enrollments_student,
      attendance_records_student,
      invoices_student,
      assessment_results_student,
      organization,
      campus,
      photo,
    ] = await Promise.all([
      students.getGuardians_student({ transaction }),
      students.getClass_enrollments_student({ transaction }),
      students.getAttendance_records_student({ transaction }),
      students.getInvoices_student({ transaction }),
      students.getAssessment_results_student({ transaction }),
      students.getOrganization({ transaction }),
      students.getCampus({ transaction }),
      students.getPhoto({ transaction }),
    ]);
    output.guardians_student = guardians_student;
    output.class_enrollments_student = class_enrollments_student;
    output.attendance_records_student = attendance_records_student;
    output.invoices_student = invoices_student;
    output.assessment_results_student = assessment_results_student;
    output.organization = organization;
    output.campus = campus;
    output.photo = photo;

    return output;
  }

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

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.student_number) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('students', 'student_number', filter.student_number),
      };
    }
    if (filter.first_name) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('students', 'first_name', filter.first_name),
      };
    }
    if (filter.last_name) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('students', 'last_name', filter.last_name),
      };
    }
    if (filter.email) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('students', 'email', filter.email),
      };
    }
    if (filter.phone) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('students', 'phone', filter.phone),
      };
    }
    if (filter.address) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('students', 'address', filter.address),
      };
    }
    if (filter.date_of_birthRange) {
      const [start, end] = filter.date_of_birthRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, date_of_birth: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          date_of_birth: {
            ...(typeof where.date_of_birth === 'object'
              ? where.date_of_birth
              : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.enrollment_dateRange) {
      const [start, end] = filter.enrollment_dateRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, enrollment_date: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          enrollment_date: {
            ...(typeof where.enrollment_date === 'object'
              ? where.enrollment_date
              : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    if (filter.gender) {
      where = { ...where, gender: filter.gender };
    }
    if (filter.status) {
      where = { ...where, status: filter.status };
    }
    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.students.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.students,
      'student_number',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default StudentsDBApi;
