import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { getAuthenticatedStore, unauthorizedResponse } from '@/lib/auth/storeContext';
import { ShopifyClient } from '@/lib/shopify/client';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  try {
    // 1. Strictly authenticate and resolve the single caller's store
    const shop = await getAuthenticatedStore(req);
    if (!shop) {
      return unauthorizedResponse(req);
    }

    // 2. Fetch dashboard metrics exclusively for this authenticated store
    const metrics = await db.getStoreDashboardMetrics(shop.id);

    // 3. Fetch live store metadata (timezone, currency)
    let timezone = 'UTC';
    let currency = 'USD';
    try {
      const client = new ShopifyClient(shop.shopify_domain);
      const info = await client.getShopInfo();
      if (info.ianaTimezone) {
        timezone = info.ianaTimezone;
      }
      if (info.currencyCode) {
        currency = info.currencyCode;
      }
    } catch {
      timezone = 'UTC';
    }

    return NextResponse.json({
      success: true,
      store: {
        id: shop.id,
        domain: shop.shopify_domain,
        status: shop.status,
        plan: shop.plan,
        installedAt: shop.installed_at,
        scopes: shop.scopes,
        timezone,
        currency,
      },
      shops: [
        {
          id: shop.id,
          domain: shop.shopify_domain,
          status: shop.status,
          plan: shop.plan,
          installedAt: shop.installed_at,
          scopes: shop.scopes,
        },
      ],
      totalStores: 1,
      metrics,
    });
  } catch (err) {
    return NextResponse.json(
      { success: false, error: err instanceof Error ? err.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
