import { NextRequest, NextResponse } from "next/server";
import { stripe } from "@/lib/stripe";
import { logger } from "@/lib/logger";
import { convexMutation, convexQuery } from "@/lib/convex-client";
import { upsertConvexSubscriptionByStripeId } from "@/lib/convex-billing-state";

const ADMIN_KEY = process.env.ADMIN_SYNC_KEY || "mawidi-admin-sync-2026";

export async function POST(request: NextRequest) {
  try {
    const adminKey = request.headers.get("x-admin-key");
    if (adminKey !== ADMIN_KEY) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await request.json();
    const { email } = body;

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

    const user = await convexQuery<Record<string, unknown>>(
      "auth/queries:getUserByEmail",
      { email },
    );

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

    const customers = await stripe.customers.list({ email, limit: 1 });
    if (customers.data.length === 0) {
      return NextResponse.json(
        { error: "Stripe customer not found" },
        { status: 404 },
      );
    }

    const customer = customers.data[0];
    const subscriptions = await stripe.subscriptions.list({
      customer: customer.id,
      status: "all",
    });

    let activeSubscription = subscriptions.data.find(
      (s) => s.status === "active",
    );
    if (!activeSubscription) {
      activeSubscription = subscriptions.data.find(
        (s) => s.status === "trialing",
      );
    }

    if (!activeSubscription) {
      return NextResponse.json(
        { error: "No active/trialing subscription found" },
        { status: 404 },
      );
    }

    const price = activeSubscription.items.data[0]?.price;
    const billingPeriod =
      price?.recurring?.interval === "year" ? "yearly" : "monthly";
    const tierId = activeSubscription.metadata?.tier_id || "tier5";
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const subData = activeSubscription as any;

    const currentPeriodEnd = subData.current_period_end
      ? subData.current_period_end * 1000
      : Date.now() + 30 * 24 * 60 * 60 * 1000;
    const trialEndsAt = subData.trial_end
      ? subData.trial_end * 1000
      : undefined;

    const subscriptionId = await upsertConvexSubscriptionByStripeId({
      userId: user._id as string,
      stripeCustomerId: customer.id,
      stripeSubscriptionId: activeSubscription.id,
      stripePriceId: price?.id || "",
      tierId,
      status: activeSubscription.status,
      billingPeriod,
      currentPeriodEnd,
      trialEndsAt,
      cancelAtPeriodEnd: activeSubscription.cancel_at_period_end || false,
    });

    await convexMutation("auth/mutations:updateUserNoAuth", {
      userId: user._id as string,
      stripeCustomerId: customer.id,
    });

    if (activeSubscription.status === "active") {
      const trialingSubscriptions = subscriptions.data.filter(
        (s) => s.id !== activeSubscription.id && s.status === "trialing",
      );

      for (const oldSubscription of trialingSubscriptions) {
        try {
          await stripe.subscriptions.cancel(oldSubscription.id);
        } catch (error) {
          logger.warn("[Admin Sync] Failed to cancel old subscription", {
            id: oldSubscription.id,
            error,
          });
        }
      }
    }

    return NextResponse.json({
      success: true,
      user: {
        id: user.appUserId ?? user._id,
        email: user.email,
      },
      subscription: {
        id: subscriptionId,
        stripeSubscriptionId: activeSubscription.id,
        status: activeSubscription.status,
        tierId,
        billingPeriod,
      },
      message: `Subscription synced. Status is now: ${activeSubscription.status}`,
    });
  } catch (error) {
    logger.error("[Admin Sync] Error", error);
    return NextResponse.json(
      {
        error: "Sync failed",
        details: error instanceof Error ? error.message : "Unknown error",
      },
      { status: 500 },
    );
  }
}
