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

type MessageRecipientsData = Partial<
  InferCreationAttributes<MessageRecipients>
> & {
  organization?: string | null;
  message?: string | null;
};

interface MessageRecipientsFilter {
  limit?: number | string;
  page?: number | string;
  id?: string;
  recipient_label?: string;
  destination?: string;
  delivered_atRange?: Array<string | null | undefined>;
  read_atRange?: Array<string | null | undefined>;
  active?: boolean | string;
  recipient_type?: string;
  delivery_status?: string;
  message?: string;
  organization?: string;
  createdAtRange?: Array<string | null | undefined>;
  field?: string;
  sort?: string;
}

const NO_USER: CurrentUser = { id: null };

class Message_recipientsDBApi {
  static async create(
    data: MessageRecipientsData,
    options?: DbApiOptions,
  ): Promise<MessageRecipients> {
    const currentUser = options?.currentUser ?? NO_USER;
    const transaction = options?.transaction;

    const message_recipients = await db.message_recipients.create(
      {
        id: data.id || undefined,
        recipient_type: data.recipient_type || null,
        recipient_label: data.recipient_label || null,
        destination: data.destination || null,
        delivery_status: data.delivery_status || null,
        delivered_at: data.delivered_at || null,
        read_at: data.read_at || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await message_recipients.setOrganization(
      currentUser.organizationId ?? undefined,
      { transaction },
    );
    await message_recipients.setMessage(data.message ?? undefined, {
      transaction,
    });

    return message_recipients;
  }

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

    const message_recipientsData = data.map((item, index) => ({
      id: item.id || undefined,
      recipient_type: item.recipient_type || null,
      recipient_label: item.recipient_label || null,
      destination: item.destination || null,
      delivery_status: item.delivery_status || null,
      delivered_at: item.delivered_at || null,
      read_at: item.read_at || null,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * BULK_IMPORT_TIMESTAMP_STEP_MS),
    }));

    return db.message_recipients.bulkCreate(message_recipientsData, {
      transaction,
    });
  }

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

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

    if (!message_recipients) {
      return null;
    }

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

    if (data.recipient_type !== undefined)
      updatePayload.recipient_type = data.recipient_type;
    if (data.recipient_label !== undefined)
      updatePayload.recipient_label = data.recipient_label;
    if (data.destination !== undefined)
      updatePayload.destination = data.destination;
    if (data.delivery_status !== undefined)
      updatePayload.delivery_status = data.delivery_status;
    if (data.delivered_at !== undefined)
      updatePayload.delivered_at = data.delivered_at;
    if (data.read_at !== undefined) updatePayload.read_at = data.read_at;

    updatePayload.updatedById = currentUser.id;

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

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

    return message_recipients;
  }

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

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

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

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

    if (!message_recipients) {
      return null;
    }

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

    const [organization, message] = await Promise.all([
      message_recipients.getOrganization({ transaction }),
      message_recipients.getMessage({ transaction }),
    ]);
    output.organization = organization;
    output.message = message;

    return output;
  }

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

    if (filter.id) {
      where = { ...where, id: Utils.uuid(filter.id) };
    }
    if (filter.recipient_label) {
      where = {
        ...where,
        [Op.and]: Utils.ilike(
          'message_recipients',
          'recipient_label',
          filter.recipient_label,
        ),
      };
    }
    if (filter.destination) {
      where = {
        ...where,
        [Op.and]: Utils.ilike(
          'message_recipients',
          'destination',
          filter.destination,
        ),
      };
    }
    if (filter.delivered_atRange) {
      const [start, end] = filter.delivered_atRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, delivered_at: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          delivered_at: {
            ...(typeof where.delivered_at === 'object'
              ? where.delivered_at
              : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.read_atRange) {
      const [start, end] = filter.read_atRange;
      if (start !== undefined && start !== null && start !== '') {
        where = { ...where, read_at: { [Op.gte]: start } };
      }
      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          read_at: {
            ...(typeof where.read_at === 'object' ? where.read_at : {}),
            [Op.lte]: end,
          },
        };
      }
    }
    if (filter.active !== undefined) {
      where = {
        ...where,
        active: filter.active === true || filter.active === 'true',
      };
    }
    if (filter.recipient_type) {
      where = { ...where, recipient_type: filter.recipient_type };
    }
    if (filter.delivery_status) {
      where = { ...where, delivery_status: filter.delivery_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.message_recipients.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.message_recipients,
      'recipient_label',
      query,
      limit,
      offset,
      globalAccess,
      organizationId,
    );
  }
}

export default Message_recipientsDBApi;
