import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";
import { withRateLimit, rateLimiters } from "@/lib/rate-limiter";
import { z } from "zod";
import { withCSRF } from "@/lib/csrf";

// Validation schema
const companyInfoSchema = z.object({
  companyName: z.string().min(2).max(100),
  industry: z.string().min(1),
  companySize: z.string().min(1),
  country: z.string().min(1),
  city: z.string().optional(),
  phoneNumber: z.string().optional(),
  website: z.string().url().optional().or(z.literal("")),
  userId: z.string().optional(), // Will use session user ID
});

// Force dynamic rendering
export const dynamic = "force-dynamic";
export const runtime = "nodejs";

async function handler(req: NextRequest) {
  try {
    // Get authenticated session
    const session = await auth();
    if (!session?.user?.email) {
      // Try to get email from request body if not authenticated
      const body = await req.json();
      const userEmail = body.email;

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

      // Find user by email instead of session
      const user = await prisma.users.findUnique({
        where: { email: userEmail.toLowerCase() },
      });

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

      // Continue with user from database
      return await updateCompanyInfo(req, user.id, body);
    }

    // User is authenticated via session
    const body = await req.json();
    return await updateCompanyInfo(req, session.user.id as string, body);
  } catch (error) {
    logger.error("Error in company info handler", error);
    return NextResponse.json(
      { error: "Failed to save company information" },
      { status: 500 },
    );
  }
}

async function updateCompanyInfo(req: NextRequest, userId: string, body: any) {
  try {
    // Validate request body
    const validation = companyInfoSchema.safeParse(body);

    if (!validation.success) {
      logger.warn("Invalid company info data", {
        errors: validation.error.errors,
        userId: userId,
      });
      return NextResponse.json(
        { error: "Invalid data", details: validation.error.errors },
        { status: 400 },
      );
    }

    const data = validation.data;

    // Format website URL if provided
    let websiteUrl = data.website;
    if (websiteUrl && !websiteUrl.startsWith("http")) {
      websiteUrl = `https://${websiteUrl}`;
    }

    // Update user record with company information
    const updatedUser = await prisma.users.update({
      where: { id: userId },
      data: {
        companyName: data.companyName,
        industry: data.industry,
        companySize: data.companySize,
        country: data.country,
        city: data.city || null,
        phoneNumber: data.phoneNumber || body.phoneNumber || null,
        website: websiteUrl || null,
        selectedPackage: body.selectedPlan || null,
        updatedAt: new Date(),
      },
    });

    // Log audit event
    const ip =
      req.headers.get("x-forwarded-for") ||
      req.headers.get("x-real-ip") ||
      "127.0.0.1";
    await prisma.audit_logs.create({
      data: {
        id: crypto.randomUUID(), // Generate unique ID for audit log
        userId,
        type: "company_info_update",
        action: "User updated company information",
        success: true,
        ip,
        userAgent: req.headers.get("user-agent") || undefined,
        metadata: {
          companyName: data.companyName,
          industry: data.industry,
        },
      },
    });

    logger.info("Company info updated successfully", {
      userId,
      companyName: data.companyName,
    });

    return NextResponse.json({
      success: true,
      message: "Company information saved successfully",
    });
  } catch (error) {
    logger.error("Error updating company info", error);
    return NextResponse.json(
      { error: "Failed to save company information" },
      { status: 500 },
    );
  }
}

// Apply CSRF protection and rate limiting
export const POST = withCSRF(withRateLimit(handler, rateLimiters.authGeneral));
