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

export async function GET(req: Request) {
  const auth = await authenticateDeveloperRequest(req, { section: "reminders" });
  if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const url = new URL(req.url);
  const limit = Math.min(Math.max(Number(url.searchParams.get("limit") || 50), 1), 100);
  const status = url.searchParams.get("status");

  let reminders: Reminder[];
  if (auth.workspaceTeamId) {
    const { rows } = status
      ? await sql<Reminder>`
          SELECT * FROM reminders WHERE team_id = ${auth.workspaceTeamId} AND status = ${status}
          ORDER BY remind_at LIMIT ${limit}
        `
      : await sql<Reminder>`
          SELECT * FROM reminders WHERE team_id = ${auth.workspaceTeamId}
          ORDER BY remind_at LIMIT ${limit}
        `;
    reminders = rows;
  } else {
    const { rows } = status
      ? await sql<Reminder>`
          SELECT * FROM reminders
          WHERE team_id IS NULL AND user_id = ${auth.workspaceUserId} AND status = ${status}
          ORDER BY remind_at LIMIT ${limit}
        `
      : await sql<Reminder>`
          SELECT * FROM reminders WHERE team_id IS NULL AND user_id = ${auth.workspaceUserId}
          ORDER BY remind_at LIMIT ${limit}
        `;
    reminders = rows;
  }

  return NextResponse.json({ reminders });
}

export async function POST(req: Request) {
  const auth = await authenticateDeveloperRequest(req, { write: true, section: "reminders" });
  if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json();
  if (!body?.title || !body?.remind_at) {
    return NextResponse.json({ error: "title and remind_at are required" }, { status: 400 });
  }

  const title = String(body.title).trim();
  const remind_at = String(body.remind_at);
  const bodyText = typeof body.body === "string" ? body.body : null;
  const recurrence_rule: ReminderRecurrenceRule =
    body.recurrence_rule === "daily" ||
    body.recurrence_rule === "weekly" ||
    body.recurrence_rule === "monthly" ||
    body.recurrence_rule === "weekdays"
      ? body.recurrence_rule
      : "none";
  const recurrence_days = Array.isArray(body.recurrence_days)
    ? body.recurrence_days.filter((day: unknown) => Number.isInteger(day) && (day as number) >= 0 && (day as number) <= 6)
    : [];
  const status: ReminderStatus =
    body.status === "scheduled" ||
    body.status === "triggered" ||
    body.status === "snoozed" ||
    body.status === "done" ||
    body.status === "cancelled"
      ? body.status
      : "scheduled";

  let data: Reminder;
  try {
    const { rows } = await sql<Reminder>`
      INSERT INTO reminders (user_id, team_id, title, body, remind_at, status, recurrence_rule, recurrence_days, source_type)
      VALUES (
        ${auth.workspaceUserId}, ${auth.workspaceTeamId}, ${title}, ${bodyText}, ${remind_at},
        ${status}, ${recurrence_rule}, ${recurrence_days}, 'manual'
      )
      RETURNING *
    `;
    data = rows[0];
  } catch (error) {
    const msg = error instanceof Error ? error.message : "Reminder could not be created";
    return NextResponse.json({ error: msg }, { status: 400 });
  }

  return NextResponse.json({ reminder: data }, { status: 201 });
}
