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

export const dynamic = 'force-dynamic';

async function resolveShopForRequest(req: NextRequest, bodyShop?: string): Promise<ShopRecord | null> {
  const url = new URL(req.url);
  const explicitShop = url.searchParams.get('shop') || url.searchParams.get('shopify_domain') || bodyShop;

  if (explicitShop) {
    const clean = explicitShop.trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '');
    const domain = clean.includes('.') ? clean : `${clean}.myshopify.com`;
    let shop = await db.getShopByDomain(domain);
    if (!shop) {
      try {
        const baseName = domain.split('.')[0] || 'Shopify Store';
        shop = await db.upsertShop({
          id: `shop_${clean.replace(/[^a-zA-Z0-9]/g, '_')}`,
          shopify_domain: domain,
          shop_name: baseName,
          status: 'installed',
          plan: 'growth',
          access_token_encrypted: '',
          scopes: ['read_products', 'write_pixels'],
          installed_at: new Date().toISOString(),
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString(),
        });
      } catch (err) {
        console.error('Failed to auto-provision shop in /api/pixels/[id]:', err);
      }
    }
    if (shop) return shop;
  }

  const authShop = await getAuthenticatedStore(req);
  if (authShop) return authShop;

  return db.getDefaultShop();
}

export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const shop = await resolveShopForRequest(req);
    if (!shop) return unauthorizedResponse(req);

    const pixelId = params.id;
    const pixel = await db.getPixelById(pixelId);
    if (!pixel || pixel.shop_id !== shop.id) {
      return NextResponse.json({ success: false, error: 'Pixel not found' }, { status: 404 });
    }

    return NextResponse.json({ success: true, pixel });
  } catch (err: any) {
    return NextResponse.json({ success: false, error: err?.message || 'Server error' }, { status: 500 });
  }
}

export async function PATCH(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const body = await req.json().catch(() => ({}));
    const shop = await resolveShopForRequest(req, body.shop || body.shopify_domain);
    if (!shop) return unauthorizedResponse(req);

    const id = params.id;
    const existing = await db.getPixelById(id);
    if (!existing || existing.shop_id !== shop.id) {
      return NextResponse.json({ success: false, error: 'Pixel not found' }, { status: 404 });
    }

    const calculatedStatus: 'active' | 'paused' | 'error' =
      body.status ||
      (body.is_active !== undefined ? (body.is_active ? 'active' : 'paused') :
      (body.isActive !== undefined ? (body.isActive ? 'active' : 'paused') : existing.status));

    const encryptedToken = body.accessToken && body.accessToken.trim()
      ? encrypt(body.accessToken.trim())
      : (body.access_token_encrypted !== undefined ? body.access_token_encrypted : existing.access_token_encrypted);

    const updated = await db.upsertPixel({
      ...existing,
      pixel_name: body.pixelName !== undefined ? body.pixelName.trim() : (body.pixel_name !== undefined ? body.pixel_name.trim() : existing.pixel_name),
      target_collection: body.targetCollection !== undefined ? body.targetCollection : (body.target_collection !== undefined ? body.target_collection : existing.target_collection),
      pages_config: body.pages_config !== undefined ? body.pages_config : existing.pages_config,
      capi_enabled: body.capiEnabled !== undefined ? Boolean(body.capiEnabled) : (body.capi_enabled !== undefined ? Boolean(body.capi_enabled) : existing.capi_enabled),
      capi_status: body.capi_status !== undefined ? body.capi_status : existing.capi_status,
      access_token_encrypted: encryptedToken,
      test_event_code: body.testEventCode !== undefined ? body.testEventCode : existing.test_event_code,
      status: calculatedStatus,
      is_active: calculatedStatus === 'active',
      verification_status: body.verification_status !== undefined ? body.verification_status : existing.verification_status,
      updated_at: new Date().toISOString(),
    });

    return NextResponse.json({ success: true, pixel: updated, message: 'Pixel updated successfully' });
  } catch (err: any) {
    return NextResponse.json({ success: false, error: err?.message || 'Failed to update pixel' }, { status: 500 });
  }
}

export async function DELETE(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const shop = await resolveShopForRequest(req);
    if (!shop) return unauthorizedResponse(req);

    const id = params.id;
    const success = await db.deletePixel(id, shop.id);
    return NextResponse.json({
      success,
      message: success ? 'Pixel deleted successfully' : 'Pixel not found',
    });
  } catch (err: any) {
    return NextResponse.json({ success: false, error: err?.message || 'Failed to delete pixel' }, { status: 500 });
  }
}
