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

type AssessmentResultsData = Partial<
  InferCreationAttributes<AssessmentResults>
> & {
  organization?: string | null;
  assessment?: string | null;
  student?: string | null;
};

interface AssessmentResultsFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  remarks?: string;
  scoreRange?: Array<number | string | null | undefined>;
  active?: boolean | string;
  grade_letter?: string;
  assessment?: string;
  student?: string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

class Assessment_resultsDBApi {
  static async create(
    data: AssessmentResultsData,
    options?: DbApiOptions,
  ): Promise<AssessmentResults> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const assessment_results = await db.assessment_results.create(
      {
        id: data.id || undefined,
        score: data.score || null,
        grade_letter: data.grade_letter || null,
        remarks: data.remarks || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await assessment_results.setOrganization(
      currentUser.organizationId ?? undefined,
      { transaction },
    );
    await assessment_results.setAssessment(data.assessment ?? undefined, {
      transaction,
    });

    return assessment_results;
  }

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

    const assessment_resultsData = data.map((item, index) => ({
      id: item.id || undefined,
      score: item.score || null,
      grade_letter: item.grade_letter || null,
      remarks: item.remarks || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * BULK_IMPORT_TIMESTAMP_STEP_MS),
    }));

    return db.assessment_results.bulkCreate(assessment_resultsData, {
      transaction,
    });
  }

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

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

    if (!assessment_results) {
      return null;
    }

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

    if (data.score !== undefined) updatePayload.score = data.score;
    if (data.grade_letter !== undefined)
      updatePayload.grade_letter = data.grade_letter;
    if (data.remarks !== undefined) updatePayload.remarks = data.remarks;

    updatePayload.updatedById = currentUser.id;

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

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

    return assessment_results;
  }

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

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

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

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

    if (!assessment_results) {
      return null;
    }

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

    const [organization, assessment] = await Promise.all([
      assessment_results.getOrganization({ transaction }),
      assessment_results.getAssessment({ transaction }),
    ]);
    output.organization = organization;
    output.assessment = assessment;

    return output;
  }

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

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

export default Assessment_resultsDBApi;
