import { NextResponse } from "next/server";
import { authenticateDeveloperRequest } from "@/lib/developers/auth";
import { sql } from "@/lib/db/postgres";
import type { Reminder, ReminderStatus } from "@/types";

async function loadOwnedReminder(
  id: string,
  workspaceUserId: string,
  workspaceTeamId: string | null
) {
  const { rows } = workspaceTeamId
    ? await sql<Reminder>`SELECT * FROM reminders WHERE id = ${id} AND team_id = ${workspaceTeamId} LIMIT 1`
    : await sql<Reminder>`SELECT * FROM reminders WHERE id = ${id} AND team_id IS NULL AND user_id = ${workspaceUserId} LIMIT 1`;
  return rows[0] ?? null;
}

export async function PATCH(req: Request, context: { params: Promise<{ id: string }> }) {
  const auth = await authenticateDeveloperRequest(req, { write: true, section: "reminders" });
  if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await context.params;
  const current = await loadOwnedReminder(id, auth.workspaceUserId, auth.workspaceTeamId);
  if (!current) return NextResponse.json({ error: "Reminder not found" }, { status: 404 });

  const body = await req.json();
  const title = typeof body.title === "string" && body.title.trim() ? body.title.trim() : current.title;
  const bodyText = body.body !== undefined ? (typeof body.body === "string" ? body.body : null) : current.body;
  const remind_at = typeof body.remind_at === "string" ? body.remind_at : current.remind_at;
  const status: ReminderStatus =
    body.status === "scheduled" ||
    body.status === "triggered" ||
    body.status === "snoozed" ||
    body.status === "done" ||
    body.status === "cancelled"
      ? body.status
      : current.status;
  const snoozed_until = body.snoozed_until !== undefined ? (typeof body.snoozed_until === "string" ? body.snoozed_until : null) : current.snoozed_until;
  const completed_at = status === "done" ? current.completed_at || new Date().toISOString() : status === current.status ? current.completed_at : null;

  const { rows } = await sql<Reminder>`
    UPDATE reminders SET
      title = ${title},
      body = ${bodyText},
      remind_at = ${remind_at},
      status = ${status},
      snoozed_until = ${snoozed_until},
      completed_at = ${completed_at}
    WHERE id = ${id}
    RETURNING *
  `;

  return NextResponse.json({ reminder: rows[0] });
}

export async function DELETE(req: Request, context: { params: Promise<{ id: string }> }) {
  const auth = await authenticateDeveloperRequest(req, { write: true, section: "reminders" });
  if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await context.params;
  const current = await loadOwnedReminder(id, auth.workspaceUserId, auth.workspaceTeamId);
  if (!current) return NextResponse.json({ error: "Reminder not found" }, { status: 404 });

  await sql`DELETE FROM reminders WHERE id = ${id}`;
  return NextResponse.json({ success: true });
}
