import type { Pool } from 'pg';

import {
  reminderSendPayloadSchema,
  REMINDER_SEND_ACTIONS,
  type ReminderSendAction,
  type ReminderSendPayload,
} from '@/entities/reminderSendItem';
import { getDb } from '@/shared/db';
import {
  createSendQueueRepo,
  type PendingItem,
  type SendResultInput,
} from '@/shared/sendQueue';

const repo = createSendQueueRepo({
  tableName: 'macsync.reminder_send_queue',
  payloadSchema: reminderSendPayloadSchema,
  allowedActions: REMINDER_SEND_ACTIONS,
});

export interface EnqueueReminderInput {
  deviceId: string;
  action: ReminderSendAction;
  payload: ReminderSendPayload;
}

export async function enqueueReminderChange(
  input: EnqueueReminderInput,
  db: Pool = getDb(),
): Promise<{ id: string }> {
  try {
    return await repo.enqueue(db, input);
  } catch (err) {
    throw new Error(
      `enqueueReminderChange failed for device ${input.deviceId} (${input.action}): ${
        err instanceof Error ? err.message : String(err)
      }`,
      { cause: err },
    );
  }
}

export async function listPendingReminderSends(
  deviceId: string,
  db: Pool = getDb(),
): Promise<PendingItem<ReminderSendPayload>[]> {
  try {
    return await repo.listPending(db, deviceId);
  } catch (err) {
    throw new Error(
      `listPendingReminderSends failed for device ${deviceId}: ${
        err instanceof Error ? err.message : String(err)
      }`,
      { cause: err },
    );
  }
}

export async function markReminderSendResult(
  input: SendResultInput,
  db: Pool = getDb(),
): Promise<void> {
  try {
    await repo.markResult(db, input);
  } catch (err) {
    throw new Error(
      `markReminderSendResult failed for id ${input.id}: ${
        err instanceof Error ? err.message : String(err)
      }`,
      { cause: err },
    );
  }
}
