import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import DOMPurify from "isomorphic-dompurify";
import validator from "validator";
import { logger } from "@/lib/logger";
import { getClientIp } from "@/lib/utils/ip-extraction";
import { createId } from "@paralleldrive/cuid2";
import { prisma } from "@/lib/db";
import { contactSubmissionsAdapter } from "@/lib/adapters/contacts";
import { withSecureRoute } from "@/lib/api-security";
import { rateLimiters } from "@/lib/rate-limiter";
import { sendEmail } from "@/lib/email";

const GCC_COUNTRIES = ["SA", "AE", "QA", "KW", "BH", "OM"] as const;
const COMPANY_TYPES = [
  "it_provider",
  "business_consultant",
  "medical_equipment",
  "marketing_agency",
  "other",
] as const;

const partnerSchema = z.object({
  name: z.string().min(2, "Name must be at least 2 characters").max(100),
  email: z.string().email("Invalid email address"),
  phone: z.string().min(5).max(20),
  company: z.string().min(2).max(200),
  companyType: z.enum(COMPANY_TYPES),
  website: z.string().url().max(500).optional().or(z.literal("")),
  country: z.enum(GCC_COUNTRIES),
  language: z.enum(["ar", "en"]).default("en"),
  recaptchaToken: z.string().optional(),
});

/**
 * Generate a unique partner referral code from company name
 */
function generatePartnerCode(company: string): string {
  const slug = company
    .replace(/[^a-zA-Z0-9\s]/g, "")
    .trim()
    .split(/\s+/)
    .slice(0, 2)
    .join("-")
    .toUpperCase()
    .slice(0, 12);
  const suffix = Math.random().toString(36).substring(2, 6).toUpperCase();
  return `P-${slug}-${suffix}`;
}

/**
 * Verify reCAPTCHA token with Google
 */
async function verifyRecaptcha(
  token: string,
): Promise<{ success: boolean; score: number }> {
  const secretKey = process.env.RECAPTCHA_SECRET_KEY;
  const threshold = parseFloat(process.env.RECAPTCHA_SCORE_THRESHOLD || "0.5");
  const isDevelopment = process.env.NODE_ENV !== "production";

  if (isDevelopment) {
    return { success: true, score: 1.0 };
  }

  if (!secretKey || !token) {
    return { success: false, score: 0 };
  }

  try {
    const response = await fetch(
      "https://www.google.com/recaptcha/api/siteverify",
      {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: `secret=${secretKey}&response=${token}`,
      },
    );
    const data = await response.json();
    return {
      success: data.success && data.score >= threshold,
      score: data.score || 0,
    };
  } catch (error) {
    logger.error("reCAPTCHA verification failed", { error });
    return { success: false, score: 0 };
  }
}

/**
 * POST /api/partners
 * Register a new partner application.
 * Creates a contact_submissions entry (for staff dashboard visibility)
 * and a staff_alert for admin review. Full partner account activation
 * happens after admin approval.
 */
export const POST = withSecureRoute(
  async (request: NextRequest) => {
    try {
      const body = await request.json();
      const ip = getClientIp(request);

      const validation = partnerSchema.safeParse(body);
      if (!validation.success) {
        return NextResponse.json(
          { error: "Invalid input", details: validation.error.errors },
          { status: 400 },
        );
      }

      const {
        name,
        email,
        phone,
        company,
        companyType,
        website,
        country,
        language,
        recaptchaToken,
      } = validation.data;

      // Verify reCAPTCHA
      if (recaptchaToken) {
        const recaptchaResult = await verifyRecaptcha(recaptchaToken);
        if (!recaptchaResult.success) {
          logger.warn("Partner form reCAPTCHA failed", {
            ip,
            score: recaptchaResult.score,
          });
          return NextResponse.json(
            { error: "Bot verification failed. Please try again." },
            { status: 400 },
          );
        }
      }

      if (!validator.isEmail(email)) {
        return NextResponse.json(
          { error: "Invalid email address" },
          { status: 400 },
        );
      }

      // Sanitize inputs
      const sanitizedName = DOMPurify.sanitize(name);
      const sanitizedEmail = validator.normalizeEmail(email) || email;
      const sanitizedCompany = DOMPurify.sanitize(company);
      const sanitizedPhone = DOMPurify.sanitize(phone);
      const sanitizedWebsite = website ? DOMPurify.sanitize(website) : null;

      // Check for duplicate partner application
      const existingPartner = await contactSubmissionsAdapter.findFirst({
        where: {
          email: sanitizedEmail,
          topic: "partner_application",
        },
      });

      if (existingPartner) {
        return NextResponse.json({
          success: true,
          message: "Application already received",
          referralCode: null,
          isReturning: true,
        });
      }

      // Generate a provisional referral code
      const referralCode = generatePartnerCode(sanitizedCompany);

      // Save as contact submission for staff dashboard visibility

      logger.info("New partner application received", {
        contactId: contact.id,
        company: sanitizedCompany,
        companyType,
        country,
        referralCode,
      });

      // Create staff alert for admin review
      await prisma.staff_alerts.create({
        data: {
          id: createId(),
          type: "NEW_CONTACT",
          title: "New Partner Application",
          message: `${sanitizedName} from ${sanitizedCompany} (${companyType}) applied to the partner program`,
          severity: "INFO",
          metadata: {
            contactId: contact.id,
            name: sanitizedName,
            email: sanitizedEmail,
            phone: sanitizedPhone,
            company: sanitizedCompany,
            companyType,
            website: sanitizedWebsite,
            country,
            referralCode,
            requiresAction: "partner_approval",
          },
        },
      });

      // Send welcome/confirmation email (fire-and-forget)
      const isAr = language === "ar";
      sendEmail(sanitizedEmail, {
        subject: isAr
          ? "شكراً لتقديمك لبرنامج شركاء موعدي"
          : "Thanks for applying to the Mawidi Partner Program",
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; direction: ${isAr ? "rtl" : "ltr"};">
            <div style="background: #16a34a; padding: 24px; text-align: center;">
              <h1 style="color: white; margin: 0; font-size: 24px;">
                ${isAr ? "برنامج شركاء موعدي" : "Mawidi Partner Program"}
              </h1>
            </div>
            <div style="padding: 24px; background: #f9fafb;">
              <p style="font-size: 16px; color: #1f2937;">
                ${isAr ? `مرحباً ${sanitizedName}،` : `Hi ${sanitizedName},`}
              </p>
              <p style="font-size: 14px; color: #4b5563; line-height: 1.6;">
                ${
                  isAr
                    ? "شكراً لاهتمامك ببرنامج شركاء موعدي! تم استلام طلبك وسيقوم فريقنا بمراجعته خلال 24-48 ساعة."
                    : "Thank you for your interest in the Mawidi Partner Program! We've received your application and our team will review it within 24-48 hours."
                }
              </p>
              <div style="background: white; border: 1px solid #e5e7eb; border-radius: 8px; padding: 16px; margin: 16px 0;">
                <h3 style="margin: 0 0 8px 0; color: #1f2937;">
                  ${isAr ? "تفاصيل الشراكة" : "Partnership Details"}
                </h3>
                <ul style="padding-left: ${isAr ? "0" : "20px"}; padding-right: ${isAr ? "20px" : "0"}; color: #4b5563; font-size: 14px;">
                  <li>${isAr ? "عمولة 20% لمدة 12 شهراً على كل إحالة" : "20% commission for 12 months on every referral"}</li>
                  <li>${isAr ? "لوحة تحكم شخصية لتتبع الإحالات" : "Personal dashboard to track your referrals"}</li>
                  <li>${isAr ? "مواد تسويقية وأدوات مبيعات" : "Marketing materials and sales tools"}</li>
                  <li>${isAr ? "دعم مخصص لفريق المبيعات" : "Dedicated partner support team"}</li>
                </ul>
              </div>
              <p style="font-size: 14px; color: #4b5563;">
                ${
                  isAr
                    ? "سنتواصل معك قريباً لتفعيل حسابك كشريك."
                    : "We'll be in touch soon to activate your partner account."
                }
              </p>
              <p style="font-size: 14px; color: #6b7280; margin-top: 24px;">
                ${isAr ? "فريق موعدي" : "The Mawidi Team"}
              </p>
            </div>
          </div>
        `,
        text: isAr
          ? `مرحباً ${sanitizedName}، شكراً لاهتمامك ببرنامج شركاء موعدي. تم استلام طلبك وسنتواصل معك خلال 24-48 ساعة.`
          : `Hi ${sanitizedName}, Thank you for applying to the Mawidi Partner Program. We've received your application and will be in touch within 24-48 hours.`,
      }).catch((err: Error) => {
        logger.error("Failed to send partner welcome email", {
          error: err.message,
          email: sanitizedEmail,
        });
      });

      return NextResponse.json({
        success: true,
        message: isAr
          ? "تم استلام طلبك بنجاح. سنتواصل معك قريباً."
          : "Application received successfully. We'll be in touch soon.",
        referralCode,
        isReturning: false,
      });
    } catch (error) {
      logger.error("Partner application error:", { error });
      return NextResponse.json(
        { error: "Failed to process request" },
        { status: 500 },
      );
    }
  },
  { rateLimiter: rateLimiters.contact },
);

/**
 * GET /api/partners?code=P-XXXXX
 * Check partner referral stats (public - for partner dashboard)
 */
export async function GET(request: NextRequest) {
  try {
    const code = request.nextUrl.searchParams.get("code");
    if (!code) {
      return NextResponse.json(
        { error: "Referral code is required" },
        { status: 400 },
      );
    }

    const referral = await prisma.referrals.findUnique({
      where: { code },
      select: {
        code: true,
        name: true,
        rewardType: true,
        rewardValue: true,
        uses: true,
        conversions: true,
        rewardsIssued: true,
        status: true,
        createdAt: true,
        lastConvertedAt: true,
      },
    });

    if (!referral) {
      return NextResponse.json(
        { error: "Referral code not found" },
        { status: 404 },
      );
    }

    return NextResponse.json({
      code: referral.code,
      name: referral.name,
      stats: {
        referrals: referral.uses,
        conversions: referral.conversions,
        conversionRate:
          referral.uses > 0
            ? Math.round((referral.conversions / referral.uses) * 100)
            : 0,
        estimatedEarnings: referral.conversions * 179 * 0.2 * 12, // 20% of £179/mo for 12 months
        rewardsIssued: referral.rewardsIssued,
      },
      status: referral.status,
      since: referral.createdAt,
      lastConversion: referral.lastConvertedAt,
    });
  } catch (error) {
    logger.error("Partner stats error:", { error });
    return NextResponse.json(
      { error: "Failed to retrieve partner stats" },
      { status: 500 },
    );
  }
}
