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

export const dynamic = 'force-dynamic';

export async function POST(request: NextRequest) {
  try {
    let shopDomain = '';
    const authStore = await getAuthenticatedStore(request);
    if (authStore) {
      shopDomain = authStore.shopify_domain;
    }

    const contentType = request.headers.get('content-type') || '';
    let requestedPlan = '';
    let returnUrl = '';

    if (contentType.includes('application/json')) {
      const body = await request.json();
      requestedPlan = body.plan || body.plan_id || '';
      returnUrl = body.return_url || '';
      if (!shopDomain && body.shop_domain) {
        shopDomain = body.shop_domain;
      }
    } else {
      const formData = await request.formData();
      requestedPlan = String(formData.get('plan') || formData.get('plan_id') || '');
      returnUrl = String(formData.get('return_url') || '');
      if (!shopDomain && formData.get('shop_domain')) {
        shopDomain = String(formData.get('shop_domain'));
      }
    }

    if (!shopDomain) {
      const url = new URL(request.url);
      shopDomain = url.searchParams.get('shop') || '';
    }

    if (!shopDomain) {
      const allShops = await db.getAllShops();
      if (allShops.length > 0) {
        shopDomain = allShops[0].shopify_domain;
      }
    }

    if (!shopDomain) {
      return NextResponse.json(
        { success: false, error: 'Shop domain could not be resolved. Please re-open the app from Shopify Admin.' },
        { status: 400 }
      );
    }

    const normalizedPlan = (requestedPlan || 'basic').toLowerCase();
    if (!['basic', 'growth', 'accelerate'].includes(normalizedPlan)) {
      return NextResponse.json(
        { success: false, error: `Invalid plan '${requestedPlan}'. Valid plans are basic, growth, accelerate.` },
        { status: 400 }
      );
    }

    const defaultReturnUrl =
      returnUrl ||
      buildAppUrl(`/api/billing/callback?shop=${encodeURIComponent(shopDomain)}&plan=${encodeURIComponent(normalizedPlan)}`);

    const result = await BillingService.createSubscription({
      shopDomainOrId: shopDomain,
      plan: normalizedPlan,
      returnUrl: defaultReturnUrl,
    });

    // Record activity log
    const shop = await BillingService.resolveShopRecord(shopDomain);
    if (shop) {
      await db.recordStoreActivity({
        id: `act_${Date.now()}_${Math.random().toString(36).substring(2, 6)}`,
        shop_id: shop.id,
        shopify_domain: shop.shopify_domain,
        action: 'subscription_initiated',
        actor: 'merchant',
        description: `Plan selection initiated for ${normalizedPlan.toUpperCase()} (Status: ${result.status})`,
        metadata: {
          plan: normalizedPlan,
          confirmationUrl: result.confirmationUrl,
          status: result.status,
        },
        created_at: new Date().toISOString(),
      });
    }

    return NextResponse.json({
      success: true,
      plan: normalizedPlan,
      confirmationUrl: result.confirmationUrl,
      subscriptionId: result.subscriptionId,
      status: result.status,
      billingAuthority: result.billingAuthority,
    });
  } catch (error: any) {
    logger.error('Failed to create subscription via billing/subscribe', { error: error.message });
    return NextResponse.json(
      { success: false, error: 'Subscription initiation failed: ' + error.message },
      { status: 500 }
    );
  }
}
