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";

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

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

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

  return NextResponse.json({ event });
}

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

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

  const body = await req.json();
  const title = typeof body.title === "string" && body.title.trim() ? body.title.trim() : current.title;
  const description = body.description !== undefined ? (typeof body.description === "string" ? body.description : null) : current.description;
  const start_time = typeof body.start_time === "string" ? body.start_time : current.start_time;
  const end_time = typeof body.end_time === "string" ? body.end_time : current.end_time;
  const all_day = typeof body.all_day === "boolean" ? body.all_day : current.all_day;
  const color = body.color !== undefined ? (typeof body.color === "string" ? body.color : null) : current.color;

  const { rows } = await sql<CalendarEvent>`
    UPDATE events SET
      title = ${title},
      description = ${description},
      start_time = ${start_time},
      end_time = ${end_time},
      all_day = ${all_day},
      color = ${color}
    WHERE id = ${id}
    RETURNING *
  `;
  const event = rows[0];

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

  return NextResponse.json({ event });
}

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

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

  await sql`DELETE FROM events WHERE id = ${id}`;

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

  return NextResponse.json({ success: true });
}
