import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { BillingService } from '@/lib/shopify/billing';
import { logger } from '@/lib/logger';
import { getAuthenticatedStore } from '@/lib/auth/storeContext';
import { APP_PATHS, buildAppUrl } from '@/config/app';

export const dynamic = 'force-dynamic';

export async function POST(request: NextRequest) {
  try {
    let body: any = {};
    try {
      body = await request.json();
    } catch {
      body = {};
    }

    const { plan_id, return_url, shop_domain } = body;

    let shop = await getAuthenticatedStore(request);
    if (!shop && shop_domain) {
      shop = await db.getShopByDomain(shop_domain);
    }
    if (!shop) {
      const allShops = await db.getAllShops();
      if (allShops.length > 0) {
        shop = allShops[0];
      }
    }

    if (!shop) {
      return NextResponse.json(
        { success: false, error: 'Unauthorized: Shop could not be determined' },
        { status: 401 }
      );
    }

    if (!plan_id) {
      return NextResponse.json(
        { success: false, error: 'plan_id is required' },
        { status: 400 }
      );
    }

    const plan = await db.getPlan(plan_id);
    if (!plan) {
      return NextResponse.json(
        { success: false, error: `Plan not found: ${plan_id}` },
        { status: 404 }
      );
    }

    // Verify plan is enabled in system
    if (plan.is_active === false) {
      return NextResponse.json(
        {
          success: false,
          error: `The ${plan.name} is currently disabled and not available for selection.`,
          isPlanDisabled: true,
        },
        { status: 400 }
      );
    }

    const defaultReturnUrl =
      return_url ||
      buildAppUrl(
        `/api/billing/callback?shop=${encodeURIComponent(shop.shopify_domain)}&plan=${encodeURIComponent(plan_id)}`
      );

    const billingResult = await BillingService.createSubscription({
      shopDomainOrId: shop.id,
      plan: plan_id,
      returnUrl: defaultReturnUrl,
    });

    // Record audit log for this shop
    await db.recordAuditLog({
      id: `audit_sub_${Date.now()}`,
      shop_id: shop.id,
      action: `Subscription updated to ${plan.name} ($${plan.price}/mo)`,
      actor: 'merchant',
      metadata: {
        previous_plan: shop.plan,
        new_plan: plan_id,
        price: plan.price,
        billing_status: billingResult.status,
      },
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
    });

    logger.info(`Shop ${shop.shopify_domain} plan select: ${plan_id} (Status: ${billingResult.status})`);

    return NextResponse.json({
      success: true,
      message: `Successfully switched to ${plan.name}`,
      plan: plan_id,
      confirmationUrl: billingResult.confirmationUrl,
      subscriptionId: billingResult.subscriptionId,
      status: billingResult.status,
      billingAuthority: billingResult.billingAuthority,
    });
  } catch (error) {
    logger.error('Failed to select plan', { error: String(error) });
    return NextResponse.json(
      { success: false, error: 'Failed to update plan: ' + String(error) },
      { status: 500 }
    );
  }
}
