/**
 * Organization Seats Add API (Admin/Manual)
 * POST - Manually add purchased seats to an organization
 *
 * This endpoint is for:
 * 1. Admin manual seat allocation
 * 2. Recovery when Stripe webhook fails
 * 3. Testing seat functionality
 *
 * Authentication: Required
 * Authorization: Organization OWNER only
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { logger } from "@/lib/logger";
import { convexMutation, convexQuery } from "@/lib/convex-client";
import { getAuthenticatedConvexUser } from "@/lib/convex-auth-state";
import { seatsAddSchema } from "@/lib/validators/api-schemas";

/**
 * POST /api/organization/seats/add
 * Manually adds seats to an organization (for testing/admin/webhook recovery)
 */
export async function POST(request: NextRequest) {
  try {
    const userEmail = await getAuthenticatedEmail(request, auth);

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

    // Parse and validate request body
    const body = await request.json();
    const parsed = seatsAddSchema.safeParse(body);

    if (!parsed.success) {
      return NextResponse.json(
        {
          success: false,
          error: parsed.error.errors.map(e => e.message).join(", "),
        },
        { status: 400 },
      );
    }

    const { quantity, reason } = parsed.data;

    const orgState = await convexQuery<{
      organization: { id: string; purchasedSeats: number };
      userRole: string;
    }>("organizations/queries:getOrganizationStateByUserId", {
      userId: user.id,
    });

    if (!user) {
      return NextResponse.json(
        { success: false, error: "User not found" },
        { status: 404 },
      );
    }

    const result = await convexMutation<{
      previousSeats: number;
      newTotal: number;
      organizationId: string;
    }>("organizations/mutations:addSeats", {
      organizationId: orgState.organization.id,
      quantity,
    });

    if (!membership) {
      return NextResponse.json(
        { success: false, error: "Only organization owners can add seats" },
        { status: 403 },
      );
    }

    const organization = membership.organization;
    const newPurchasedSeats = organization.purchasedSeats + quantity;

    // Update in Prisma
    await prisma.organizations.update({
      where: { id: organization.id },
      data: { purchasedSeats: newPurchasedSeats },
    });

    logger.info("[Seat Add] Seats manually added", {
      organizationId: organization.id,
      userId: user.id,
      quantity,
      previousSeats: organization.purchasedSeats,
      newTotal: newPurchasedSeats,
      reason: reason || "manual_add",
    });

    return NextResponse.json({
      success: true,
      message: `Successfully added ${quantity} seat(s)`,
      previousSeats: organization.purchasedSeats,
      newTotal: newPurchasedSeats,
      organizationId: organization.id,
    });
  } catch (error: any) {
    logger.error("[Seat Add] Failed to add seats", error);

    return NextResponse.json(
      { success: false, error: error.message || "Failed to add seats" },
      { status: 500 },
    );
  }
}
