import { logApiError } from "@/lib/api/security";
import { NextResponse } from "next/server";
import { createRouteClient } from "@/lib/supabase/route";
import { sql } from "@/lib/db/postgres";

export async function POST(req: Request) {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();

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

    const body = await req.json();
    const slug = String(body.slug || "").trim().toLowerCase();
    const message = String(body.message || "").trim();

    if (!slug) {
      return NextResponse.json({ error: "Organization slug is required" }, { status: 400 });
    }

    const { rows: orgRows } = await sql`
      SELECT id, name, owner_id FROM organizations WHERE slug = ${slug} LIMIT 1
    `;
    const organization = orgRows[0];

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

    if (organization.owner_id === user.id) {
      return NextResponse.json({ error: "You already own this organization" }, { status: 400 });
    }

    const [memberResult, invitationResult, existingRequestResult] = await Promise.all([
      sql`
        SELECT organization_id FROM organization_members
        WHERE organization_id = ${organization.id as string} AND user_id = ${user.id}
        LIMIT 1
      `,
      user.email
        ? sql`
            SELECT id FROM organization_invitations
            WHERE organization_id = ${organization.id as string}
              AND email = ${user.email.toLowerCase()}
              AND status = 'pending'
            LIMIT 1
          `
        : Promise.resolve({ rows: [] }),
      sql`
        SELECT id FROM organization_join_requests
        WHERE organization_id = ${organization.id as string} AND user_id = ${user.id} AND status = 'pending'
        LIMIT 1
      `,
    ]);

    if (memberResult.rows[0]) {
      return NextResponse.json({ error: "You are already a member of this organization" }, { status: 400 });
    }

    if (invitationResult.rows[0]) {
      return NextResponse.json(
        { error: "You already have a pending invitation for this organization" },
        { status: 400 }
      );
    }

    if (existingRequestResult.rows[0]) {
      return NextResponse.json(
        { error: "You already have a pending join request for this organization" },
        { status: 400 }
      );
    }

    let data: Record<string, unknown>;
    try {
      const { rows } = await sql`
        INSERT INTO organization_join_requests (organization_id, user_id, email, message)
        VALUES (${organization.id as string}, ${user.id}, ${user.email?.toLowerCase() ?? ""}, ${message})
        RETURNING *
      `;
      data = rows[0];
    } catch (insertError) {
      const msg = insertError instanceof Error ? insertError.message : "Join request could not be created";
      return NextResponse.json({ error: msg }, { status: 400 });
    }

    return NextResponse.json({
      request: data,
      organization: {
        id: organization.id,
        name: organization.name,
        slug,
      },
    });
  } catch (error) {
    logApiError("Organization join request POST error:", error);
    return NextResponse.json({ error: "Join request could not be created" }, { status: 500 });
  }
}
