import { NextResponse } from "next/server";
import { authenticateDeveloperRequest } from "@/lib/developers/auth";
import { emitWorkspaceWebhookEvent } from "@/lib/developers/webhooks";
import { logTeamAudit } from "@/lib/team-audit";
import { sql } from "@/lib/db/postgres";
import type { CalendarEvent } from "@/types";

export async function GET(req: Request) {
  const auth = await authenticateDeveloperRequest(req, { section: "events" });
  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") || 100), 1), 200);
  const start = url.searchParams.get("start");
  const end = url.searchParams.get("end");

  let events: CalendarEvent[];
  if (auth.workspaceTeamId) {
    const { rows } = start && end
      ? await sql<CalendarEvent>`
          SELECT * FROM events
          WHERE team_id = ${auth.workspaceTeamId} AND start_time >= ${start} AND start_time <= ${end}
          ORDER BY start_time LIMIT ${limit}
        `
      : await sql<CalendarEvent>`
          SELECT * FROM events WHERE team_id = ${auth.workspaceTeamId}
          ORDER BY start_time LIMIT ${limit}
        `;
    events = rows;
  } else {
    const { rows } = start && end
      ? await sql<CalendarEvent>`
          SELECT * FROM events
          WHERE team_id IS NULL AND user_id = ${auth.workspaceUserId}
            AND start_time >= ${start} AND start_time <= ${end}
          ORDER BY start_time LIMIT ${limit}
        `
      : await sql<CalendarEvent>`
          SELECT * FROM events WHERE team_id IS NULL AND user_id = ${auth.workspaceUserId}
          ORDER BY start_time LIMIT ${limit}
        `;
    events = rows;
  }

  return NextResponse.json({ events });
}

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

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

  const title = String(body.title).trim();
  const description = typeof body.description === "string" ? body.description : null;
  const start_time = String(body.start_time);
  const end_time = String(body.end_time);
  const all_day = typeof body.all_day === "boolean" ? body.all_day : false;
  const color = typeof body.color === "string" ? body.color : null;

  let data: CalendarEvent;
  try {
    const { rows } = await sql<CalendarEvent>`
      INSERT INTO events (user_id, team_id, title, description, start_time, end_time, all_day, color)
      VALUES (
        ${auth.workspaceUserId}, ${auth.workspaceTeamId}, ${title}, ${description},
        ${start_time}, ${end_time}, ${all_day}, ${color}
      )
      RETURNING *
    `;
    data = rows[0];
  } catch (error) {
    const msg = error instanceof Error ? error.message : "Event could not be created";
    return NextResponse.json({ error: msg }, { status: 400 });
  }

  await logTeamAudit(auth.admin, {
    teamId: auth.workspaceTeamId,
    actorId: auth.workspaceUserId,
    action: "event_created",
    entityType: "event",
    entityId: data.id,
    title: data.title,
  });
  await emitWorkspaceWebhookEvent({
    userId: auth.workspaceUserId,
    teamId: auth.workspaceTeamId,
    actorId: auth.workspaceUserId,
    eventType: "event.created",
    data: { event: data, source: "developer_api" },
  });

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