import { logApiError } from "@/lib/api/security";
import { NextResponse } from "next/server";
import { createRouteClient } from "@/lib/supabase/route";
import { sql } from "@/lib/db/postgres";
import { logProjectActivity } from "@/lib/project-activity";
import { logTeamAudit } from "@/lib/team-audit";

export async function GET(
  _req: Request,
  context: { params: Promise<{ token: string }> }
) {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { token } = await context.params;

    const { rows: invitationRows } = await sql`
      SELECT * FROM project_guest_invitations WHERE token = ${token} LIMIT 1
    `;
    const invitation = invitationRows[0];

    if (!invitation) {
      return NextResponse.json({ error: "Invitation not found" }, { status: 404 });
    }

    const { rows: projectRows } = await sql`
      SELECT id, name, description, icon, color FROM projects WHERE id = ${invitation.project_id as string} LIMIT 1
    `;
    const project = projectRows[0] ?? null;

    return NextResponse.json({
      invitation,
      project,
    });
  } catch (error) {
    logApiError("Project guest invitation GET error:", error);
    return NextResponse.json(
      { error: "Invitation could not be loaded" },
      { status: 500 }
    );
  }
}

export async function POST(
  req: Request,
  context: { params: Promise<{ token: string }> }
) {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { token } = await context.params;
    const body = await req.json();
    const action = body.action === "decline" ? "decline" : "accept";

    const { rows: invitationRows } = await sql`
      SELECT * FROM project_guest_invitations WHERE token = ${token} LIMIT 1
    `;
    const invitation = invitationRows[0];

    if (!invitation) {
      return NextResponse.json({ error: "Invitation not found" }, { status: 404 });
    }

    const { rows: projectRows } = await sql`
      SELECT id, name, team_id FROM projects WHERE id = ${invitation.project_id as string} LIMIT 1
    `;
    const project = projectRows[0];

    if (!project) {
      return NextResponse.json({ error: "Project not found" }, { status: 404 });
    }

    if (action === "decline") {
      try {
        await sql`
          UPDATE project_guest_invitations SET status = 'revoked' WHERE id = ${invitation.id as string}
        `;
      } catch (updateError) {
        const msg = updateError instanceof Error ? updateError.message : "Invitation could not be declined";
        return NextResponse.json({ error: msg }, { status: 400 });
      }

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

    try {
      await sql`
        INSERT INTO project_guests (project_id, user_id, role, invited_by)
        VALUES (${invitation.project_id as string}, ${user.id}, ${invitation.role as string}, ${invitation.invited_by as string})
        ON CONFLICT (project_id, user_id) DO UPDATE SET
          role = EXCLUDED.role,
          invited_by = EXCLUDED.invited_by
      `;
    } catch (guestInsertError) {
      const msg = guestInsertError instanceof Error ? guestInsertError.message : "Guest access could not be created";
      return NextResponse.json({ error: msg }, { status: 400 });
    }

    try {
      await sql`
        UPDATE project_guest_invitations SET status = 'accepted' WHERE id = ${invitation.id as string}
      `;
    } catch (invitationUpdateError) {
      const msg = invitationUpdateError instanceof Error ? invitationUpdateError.message : "Invitation could not be accepted";
      return NextResponse.json({ error: msg }, { status: 400 });
    }

    await logProjectActivity(supabase, {
      userId: user.id,
      projectId: invitation.project_id as string,
      entityType: "project",
      entityId: invitation.id as string,
      action: "project_guest_joined",
      title: String(project.name),
      details: {
        role: invitation.role,
      },
    });

    await logTeamAudit(supabase, {
      teamId: project.team_id as string | null,
      actorId: user.id,
      action: "project_guest_joined",
      entityType: "member",
      entityId: user.id,
      title: String(project.name),
      details: {
        project_id: invitation.project_id,
        role: invitation.role,
      },
    });

    return NextResponse.json({
      success: true,
      action,
      projectId: invitation.project_id,
    });
  } catch (error) {
    logApiError("Project guest invitation POST error:", error);
    return NextResponse.json(
      { error: "Invitation action could not be completed" },
      { status: 500 }
    );
  }
}
