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

type AssessmentsData = Partial<InferCreationAttributes<Assessments>> & {
  organization?: string | null;
  class_subject?: string | null;
  attachments?: FileInput | FileInput[] | null;
};

interface AssessmentsFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  name?: string;
  instructions?: string;
  calendarStart?: string;
  calendarEnd?: string;
  assigned_atRange?: Array<string | null | undefined>;
  due_atRange?: Array<string | null | undefined>;
  max_scoreRange?: Array<number | string | null | undefined>;
  active?: boolean | string;
  assessment_type?: string;
  status?: string;
  class_subject?: string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

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

class AssessmentsDBApi {
  static async create(
    data: AssessmentsData,
    options?: DbApiOptions,
  ): Promise<Assessments> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const assessments = await db.assessments.create(
      {
        id: data.id || undefined,
        name: data.name || null,
        assessment_type: data.assessment_type || null,
        assigned_at: data.assigned_at || null,
        due_at: data.due_at || null,
        max_score: data.max_score || null,
        status: data.status || null,
        instructions: data.instructions || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await assessments.setOrganization(
      currentUser.organizationId ?? undefined,
      { transaction },
    );
    await assessments.setClass_subject(data.class_subject ?? undefined, {
      transaction,
    });

    await FileDBApi.replaceRelationFiles(
      {
        belongsTo: assessmentsTableName(),
        belongsToColumn: 'attachments',
        belongsToId: assessments.id,
      },
      data.attachments,
      options,
    );

    return assessments;
  }

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

    const assessmentsData = data.map((item, index) => ({
      id: item.id || undefined,
      name: item.name || null,
      assessment_type: item.assessment_type || null,
      assigned_at: item.assigned_at || null,
      due_at: item.due_at || null,
      max_score: item.max_score || null,
      status: item.status || null,
      instructions: item.instructions || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * BULK_IMPORT_TIMESTAMP_STEP_MS),
    }));

    const assessments = await db.assessments.bulkCreate(assessmentsData, {
      transaction,
    });

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

    return assessments;
  }

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

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

    if (!assessments) {
      return null;
    }

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

    if (data.name !== undefined) updatePayload.name = data.name;
    if (data.assessment_type !== undefined)
      updatePayload.assessment_type = data.assessment_type;
    if (data.assigned_at !== undefined)
      updatePayload.assigned_at = data.assigned_at;
    if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
    if (data.max_score !== undefined) updatePayload.max_score = data.max_score;
    if (data.status !== undefined) updatePayload.status = data.status;
    if (data.instructions !== undefined)
      updatePayload.instructions = data.instructions;

    updatePayload.updatedById = currentUser.id;

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

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

    await FileDBApi.replaceRelationFiles(
      {
        belongsTo: assessmentsTableName(),
        belongsToColumn: 'attachments',
        belongsToId: assessments.id,
      },
      data.attachments,
      options,
    );

    return assessments;
  }

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

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

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

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

    if (!assessments) {
      return null;
    }

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

    const [
      assessment_results_assessment,
      organization,
      class_subject,
      attachments,
    ] = await Promise.all([
      assessments.getAssessment_results_assessment({ transaction }),
      assessments.getOrganization({ transaction }),
      assessments.getClass_subject({ transaction }),
      assessments.getAttachments({ transaction }),
    ]);
    output.assessment_results_assessment = assessment_results_assessment;
    output.organization = organization;
    output.class_subject = class_subject;
    output.attachments = attachments;

    return output;
  }

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

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.name) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('assessments', 'name', filter.name),
      };
    }
    if (filter.instructions) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('assessments', 'instructions', filter.instructions),
      };
    }
    if (filter.calendarStart && filter.calendarEnd) {
      where = {
        ...where,
        [Op.or]: [
          {
            assigned_at: {
              [Op.between]: [filter.calendarStart, filter.calendarEnd],
            },
          },
          {
            due_at: {
              [Op.between]: [filter.calendarStart, filter.calendarEnd],
            },
          },
        ],
      };
    }
    if (filter.assigned_atRange) {
      const [start, end] = filter.assigned_atRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, assigned_at: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          assigned_at: {
            ...(typeof where.assigned_at === 'object' ? where.assigned_at : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.due_atRange) {
      const [start, end] = filter.due_atRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, due_at: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          due_at: {
            ...(typeof where.due_at === 'object' ? where.due_at : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.max_scoreRange) {
      const [start, end] = filter.max_scoreRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, max_score: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          max_score: {
            ...(typeof where.max_score === 'object' ? where.max_score : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    if (filter.assessment_type) {
      where = { ...where, assessment_type: filter.assessment_type };
    }
    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.assessments.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.assessments,
      'name',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default AssessmentsDBApi;
