import { randomUUIDv7 } from 'bun';

import { touchDevice } from '@/entities/device';
import {
  countReminders,
  getLastReminderSyncAt,
  listReminders,
  upsertReminder,
} from '@/entities/reminder';
import type { ReminderFilter, ReminderRecord } from '@/entities/reminder';
import { getDb, pgRun } from '@/shared/db';

export interface ReminderPayload {
  reminderIdentifier: string;
  calendarIdentifier: string;
  title?: string | null;
  notes?: string | null;
  dueDate?: string | null;
  priority?: number | null;
  isCompleted: boolean;
  modifiedAt?: string | null;
}

export interface SyncRemindersPayload {
  reminders: ReminderPayload[];
}

export interface IReminderStats {
  totalReminders: number;
  completedReminders: number;
  openReminders: number;
  lastSyncAt: string | null;
}

export async function ingestReminders(
  deviceId: string,
  payload: SyncRemindersPayload,
): Promise<{ synced: number }> {
  try {
    const db = getDb();
    await touchDevice(db, deviceId);

    let synced = 0;
    for (const r of payload.reminders) {
      await upsertReminder(db, {
        id: randomUUIDv7(),
        deviceId,
        externalId: r.reminderIdentifier,
        calendarId: r.calendarIdentifier,
        title: r.title ?? null,
        notes: r.notes ?? null,
        dueDate: r.dueDate ?? null,
        priority: r.priority ?? null,
        isCompleted: r.isCompleted,
        modifiedAt: r.modifiedAt ?? null,
      });
      synced++;
    }
    return { synced };
  } catch (err) {
    throw new Error(
      `ingestReminders failed for device ${deviceId}: ${
        err instanceof Error ? err.message : String(err)
      }`,
      { cause: err },
    );
  }
}

export async function queryReminders(filter: ReminderFilter): Promise<readonly ReminderRecord[]> {
  try {
    return await listReminders(getDb(), filter);
  } catch (err) {
    throw new Error(
      `queryReminders failed: ${err instanceof Error ? err.message : String(err)}`,
      { cause: err },
    );
  }
}

export async function getIReminderStats(deviceId: string): Promise<IReminderStats> {
  try {
    const db = getDb();
    const total = await countReminders(db, deviceId);
    const completed = (await listReminders(db, { deviceId, isCompleted: true, limit: 100000 })).length;
    return {
      totalReminders: total,
      completedReminders: completed,
      openReminders: total - completed,
      lastSyncAt: await getLastReminderSyncAt(db, deviceId),
    };
  } catch (err) {
    throw new Error(
      `getIReminderStats failed for device ${deviceId}: ${
        err instanceof Error ? err.message : String(err)
      }`,
      { cause: err },
    );
  }
}

export async function resetReminderSync(deviceId: string): Promise<{ deleted: number }> {
  try {
    const db = getDb();
    const before = await countReminders(db, deviceId);
    await pgRun(db, 'DELETE FROM macsync.reminders WHERE device_id = $1', [deviceId]);
    return { deleted: before };
  } catch (err) {
    throw new Error(
      `resetReminderSync failed for device ${deviceId}: ${
        err instanceof Error ? err.message : String(err)
      }`,
      { cause: err },
    );
  }
}
