import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { getAuthenticatedStore } from '@/lib/auth/storeContext';
import { encrypt } from '@/lib/crypto/encryption';
import { ShopRecord } from '@/types';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  try {
    const activeShop = await getAuthenticatedStore(req);
    const allShops = await db.getAllShops();

    return NextResponse.json({
      success: true,
      activeShopDomain: activeShop?.shopify_domain || '',
      activeShopId: activeShop?.id || '',
      shops: allShops.map((s) => ({
        id: s.id,
        shopify_domain: s.shopify_domain,
        status: s.status,
        installed_at: s.installed_at,
        created_at: s.created_at,
      })),
    });
  } catch (err: any) {
    return NextResponse.json(
      { success: false, error: err.message || 'Failed to list shops' },
      { status: 500 }
    );
  }
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { shopDomain, accessToken } = body;

    if (!shopDomain || !shopDomain.trim()) {
      return NextResponse.json({ success: false, error: 'Shop domain is required' }, { status: 400 });
    }

    const cleanDomain = shopDomain.trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '');
    const existing = await db.getShopByDomain(cleanDomain);

    const now = new Date().toISOString();
    const shopRecord: ShopRecord = {
      id: existing?.id || `shop_${cleanDomain.replace(/[^a-z0-9]/g, '_')}`,
      shopify_domain: cleanDomain,
      shopify_shop_id: existing?.shopify_shop_id || `gid://shopify/Shop/${Date.now()}`,
      access_token_encrypted: accessToken ? encrypt(accessToken.trim()) : existing?.access_token_encrypted || encrypt(''),
      scopes: existing?.scopes || ['read_products', 'write_products', 'read_inventory', 'read_customer_events'],
      installed_at: existing?.installed_at || now,
      status: 'installed',
      plan: existing?.plan || 'growth',
      trial_days: existing?.trial_days || 14,
      subscription_status: existing?.subscription_status || 'active',
      created_at: existing?.created_at || now,
      updated_at: now,
    };

    const saved = await db.upsertShop(shopRecord);

    return NextResponse.json({
      success: true,
      message: `Shop ${cleanDomain} registered successfully`,
      shop: {
        id: saved.id,
        shopify_domain: saved.shopify_domain,
        status: saved.status,
      },
    });
  } catch (err: any) {
    return NextResponse.json(
      { success: false, error: err.message || 'Failed to add shop' },
      { status: 500 }
    );
  }
}
