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

export const dynamic = 'force-dynamic';

export async function GET(request: NextRequest) {
  try {
    const url = new URL(request.url);
    const shop = url.searchParams.get('shop') || '';
    const chargeId = url.searchParams.get('charge_id') || '';
    const plan = url.searchParams.get('plan') || '';
    const host = url.searchParams.get('host');

    logger.info(`Received billing return callback for shop: ${shop}, plan: ${plan}, charge_id: ${chargeId}`);

    if (shop) {
      // 1. Authoritative verification and activation via GraphQL currentAppInstallation
      try {
        await BillingService.syncSubscription(shop);
      } catch (syncErr: any) {
        logger.warn(`Billing sync failed in callback for ${shop}: ${syncErr.message}`);
        // Fallback: If mock charge or dev fallback
        if (chargeId && (chargeId.startsWith('mock_') || chargeId.startsWith('dev_fallback_'))) {
          const shopRecord = await db.getShopByDomain(shop);
          if (shopRecord && plan) {
            const dbPlan = await db.getPlan(plan);
            const price = dbPlan?.price || (plan === 'accelerate' ? 99 : 13);
            const now = new Date().toISOString();

            await db.upsertShop({
              ...shopRecord,
              plan,
              subscription_status: 'active',
              subscription_id: `sub_${chargeId}`,
              monthly_revenue: price,
              updated_at: now,
            });

            await db.upsertSubscription({
              id: `sub_${shopRecord.id}`,
              shop_id: shopRecord.id,
              shopify_domain: shop,
              shopify_subscription_id: `sub_${chargeId}`,
              plan_id: plan,
              plan_name: dbPlan?.name || `${plan.toUpperCase()} Plan`,
              status: 'active',
              billing_cycle: 'monthly',
              price,
              currency: 'USD',
              trial_days: dbPlan?.trial_days || 0,
              trial_starts_at: null,
              trial_ends_at: null,
              current_period_start: now,
              current_period_end: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
              cancelled_at: null,
              created_at: now,
              updated_at: now,
            });

            await db.recordBillingEvent({
              id: `bill_${Date.now()}_${Math.random().toString(36).substring(2, 6)}`,
              shop_id: shopRecord.id,
              shopify_domain: shop,
              subscription_id: `sub_${shopRecord.id}`,
              event_type: 'charge_activated',
              amount: price,
              currency: 'USD',
              status: 'verified',
              shopify_charge_id: `sub_${chargeId}`,
              billing_date: now,
              details: { plan, charge_id: chargeId },
              created_at: now,
            });
          }
        }
      }
    }

    const storeHandle = getStoreHandle(shop || 'quickstart-1a79b82e');
    const appHandle = process.env.SHOPIFY_APP_HANDLE || 'meta-connector';
    const embeddedAppUrl = `https://admin.shopify.com/store/${storeHandle}/apps/${appHandle}/meta-connector/pricing?sync=true&activated=true&plan=${encodeURIComponent(plan || 'growth')}`;
    const directPricingUrl = buildAppUrl(`/meta-connector/pricing?sync=true&activated=true&shop=${encodeURIComponent(shop)}&plan=${encodeURIComponent(plan)}`);

    // Top-level window breakout if returned outside the iframe
    const isTopLevelWindow = !host;
    if (isTopLevelWindow && shop) {
      return new NextResponse(
        `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Redirecting to Shopify Admin...</title>
  <script>
    try {
      if (window.top && window.top !== window) {
        window.top.location.href = ${JSON.stringify(embeddedAppUrl)};
      } else {
        window.location.href = ${JSON.stringify(embeddedAppUrl)};
      }
    } catch (e) {
      window.location.href = ${JSON.stringify(embeddedAppUrl)};
    }
  </script>
</head>
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 80vh; margin: 0; background: #f8fafc;">
  <div style="text-align: center; max-width: 440px; padding: 32px; background: white; border-radius: 12px; box-shadow: 0 4px 16px rgba(0,0,0,0.06); border: 1px solid #e2e8f0;">
    <div style="font-size: 32px; margin-bottom: 12px;">🎉</div>
    <h3 style="margin: 0 0 8px; color: #1e293b; font-size: 20px;">Subscription Activated!</h3>
    <p style="color: #64748b; font-size: 14px; margin-bottom: 20px; line-height: 1.5;">Redirecting back to your Shopify app dashboard...</p>
    <a href="${embeddedAppUrl}" target="_top" style="display: inline-block; padding: 12px 24px; background: #2563eb; color: white; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px;">
      Click here to open app &rarr;
    </a>
  </div>
</body>
</html>`,
        {
          status: 200,
          headers: { 'Content-Type': 'text/html; charset=utf-8' },
        }
      );
    }

    return NextResponse.redirect(directPricingUrl);
  } catch (err: any) {
    logger.error('Error in billing callback route', { error: err.message });
    return NextResponse.redirect(buildAppUrl('/meta-connector/pricing?error=billing_callback_failed'));
  }
}
