import { NextRequest, NextResponse } from "next/server";
import { requireStaffAuth } from "@/lib/staff-auth";
import { prisma } from "@/lib/db";
import { stripe } from "@/lib/stripe";
import { getDataSource } from "@/lib/data-source";

/**
 * POST /api/staff/users/[id]/extend-trial
 * Extend a user's trial period by specified number of weeks
 */
export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } },
) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Only admins can extend trials
    if (staffUser.role !== "ADMIN" && staffUser.role !== "SUPER_ADMIN") {
      return NextResponse.json(
        { error: "Only administrators can extend trials" },
        { status: 403 },
      );
    }

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

    // Validation
    if (!weeks || weeks < 1 || weeks > 52) {
      return NextResponse.json(
        { error: "Invalid extension period (must be 1-52 weeks)" },
        { status: 400 },
      );
    }

    // Get user with active subscription
    const user = await prisma.users.findUnique({
      where: { id: params.id },
      include: {
        subscriptions: {
          where: {
            status: { in: ["trialing", "active"] },
          },
          orderBy: { createdAt: "desc" },
          take: 1,
        },
      },
    });

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

    if (!user.subscriptions || user.subscriptions.length === 0) {
      return NextResponse.json(
        { error: "User has no active subscription" },
        { status: 400 },
      );
    }

    const subscription = user.subscriptions[0];

    // Calculate new trial end date
    const currentTrialEnd =
      subscription.trialEndsAt || subscription.currentPeriodEnd;
    if (!currentTrialEnd) {
      return NextResponse.json(
        { error: "Subscription has no trial period" },
        { status: 400 },
      );
    }

    const currentEndDate = new Date(currentTrialEnd);
    const weeksInMs = weeks * 7 * 24 * 60 * 60 * 1000;
    const newTrialEnd = new Date(currentEndDate.getTime() + weeksInMs);

    // Update in Prisma
    const updatedSubscription = await prisma.subscriptions.update({
      where: { id: subscription.id },
      data: {
        trialEndsAt: newTrialEnd,
        currentPeriodEnd: newTrialEnd,
        updatedAt: new Date(),
      },
    });

    // --- Convex data-source routing: sync trial extension ---
    if (getDataSource("billing") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        await convexMutation("billing/mutations:extendTrial", {
          subscriptionId: subscription.id,
          newTrialEnd: newTrialEnd.getTime(),
          newCurrentPeriodEnd: newTrialEnd.getTime(),
        });
      } catch (convexErr) {
        console.error(
          "Convex trial extension sync failed (non-critical):",
          convexErr,
        );
      }
    }
    // --- End Convex routing ---

    // Update in Stripe if subscription exists
    if (subscription.stripeSubscriptionId) {
      try {
        await stripe.subscriptions.update(subscription.stripeSubscriptionId, {
          trial_end: Math.floor(newTrialEnd.getTime() / 1000), // Unix timestamp
        });
        console.log(
          `✅ Stripe subscription trial extended to ${newTrialEnd.toISOString()}`,
        );
      } catch (stripeError) {
        console.error("⚠️ Stripe update failed (non-critical):", stripeError);
      }
    }

    // Create audit log

    console.log(
      `🎁 Trial extended for ${user.email} by ${weeks} weeks to ${newTrialEnd.toISOString()}`,
    );

    return NextResponse.json({
      success: true,
      message: `Trial extended by ${weeks} ${weeks === 1 ? "week" : "weeks"}`,
      newTrialEnd: newTrialEnd.toISOString(),
      subscription: {
        id: updatedSubscription.id,
        trialEndsAt: updatedSubscription.trialEndsAt,
        currentPeriodEnd: updatedSubscription.currentPeriodEnd,
      },
    });
  } catch (error) {
    console.error("❌ Failed to extend trial:", error);
    return NextResponse.json(
      { error: "Failed to extend trial" },
      { status: 500 },
    );
  }
}
