/**
 * Stripe Keys Validation API
 *
 * POST /api/staff/settings/stripe-keys/validate - Validate Stripe keys without saving
 *
 * Only accessible to ADMIN and SUPER_ADMIN staff.
 * Stripe API calls stay as-is -- no Convex wiring needed for pure validation.
 */

import { NextRequest, NextResponse } from "next/server";
import { validateStaffSession } from "@/lib/staff-session";
import { stripeKeysService } from "@/lib/services/stripe-keys.service";
import { logger } from "@/lib/logger";
import { z } from "zod";
import { getDataSource } from "@/lib/data-source";

// Validation schema
const validateKeysSchema = z.object({
  secretKey: z
    .string()
    .min(10, "Secret key is required")
    .refine(
      (key) => key.startsWith("sk_test_") || key.startsWith("sk_live_"),
      "Secret key must start with sk_test_ or sk_live_",
    ),
  publishableKey: z
    .string()
    .min(10, "Publishable key is required")
    .refine(
      (key) => key.startsWith("pk_test_") || key.startsWith("pk_live_"),
      "Publishable key must start with pk_test_ or pk_live_",
    ),
});

/**
 * POST /api/staff/settings/stripe-keys/validate
 * Validate Stripe keys without saving
 */
export async function POST(request: NextRequest) {
  try {
    const session = await validateStaffSession();
    if (!session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    if (session.role !== "ADMIN" && session.role !== "SUPER_ADMIN") {
      return NextResponse.json(
        { error: "Admin access required" },
        { status: 403 },
      );
    }

    // Data source check -- pure validation, no DB writes
    const _ds = getDataSource("billing");
    void _ds;

    const body = await request.json();
    const validationResult = validateKeysSchema.safeParse(body);

    if (!validationResult.success) {
      return NextResponse.json(
        {
          valid: false,
          error: "Invalid request: " + validationResult.error.errors[0].message,
        },
        { status: 400 },
      );
    }

    const { secretKey, publishableKey } = validationResult.data;

    const secretMode = secretKey.startsWith("sk_test_") ? "test" : "live";
    const publishableMode = publishableKey.startsWith("pk_test_")
      ? "test"
      : "live";

    if (secretMode !== publishableMode) {
      return NextResponse.json({
        valid: false,
        mode: secretMode,
        error:
          "Key mode mismatch: secret key and publishable key must both be test or both be live",
      });
    }

    // Stripe API validation stays as-is
    const validation = await stripeKeysService.validateKeys(
      secretKey,
      publishableKey,
    );

    if (!validation.valid) {
      logger.warn("Stripe key validation failed", {
        staffId: session.id,
        error: validation.error,
      });

      return NextResponse.json({
        valid: false,
        mode: validation.mode,
        error: validation.error || "Invalid Stripe keys",
      });
    }

    logger.info("Stripe keys validated successfully", {
      staffId: session.id,
      mode: validation.mode,
      accountName: validation.accountName,
    });

    return NextResponse.json({
      valid: true,
      mode: validation.mode,
      accountName: validation.accountName,
    });
  } catch (error) {
    logger.error("Failed to validate Stripe keys", { error });
    return NextResponse.json(
      {
        valid: false,
        error:
          error instanceof Error
            ? error.message
            : "Failed to validate Stripe keys",
      },
      { status: 500 },
    );
  }
}
