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

export const dynamic = 'force-dynamic';

export async function PATCH(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const shop = await getAuthenticatedStore(req);
    if (!shop) {
      return unauthorizedResponse();
    }
    const catalogId = params.id;
    if (!catalogId) {
      return NextResponse.json({ success: false, error: 'Invalid catalog ID' }, { status: 400 });
    }

    const catalog = await db.getCatalogById(catalogId);
    if (!catalog || catalog.shop_id !== shop.id) {
      return NextResponse.json({ success: false, error: 'Catalog not found' }, { status: 404 });
    }

    const body = await req.json().catch(() => ({}));
    const newAutoSyncState = body.auto_sync !== undefined ? !!body.auto_sync : !catalog.auto_sync;

    const nextSync = newAutoSyncState
      ? calculateNextSyncDate(
          catalog.schedule_type || 'daily',
          catalog.schedule_day || 'Every Monday',
          catalog.schedule_hour || 2,
          catalog.schedule_period || 'AM',
          catalog.schedule_tz || 'UTC'
        )
      : null;

    const nowIso = new Date().toISOString();

    await db.updateCatalog(catalogId, {
      auto_sync: newAutoSyncState,
      next_sync_at: nextSync,
      updated_at: nowIso,
    });

    const updated = await db.getCatalogById(catalogId);

    return NextResponse.json({
      success: true,
      catalog: updated,
    });
  } catch (err: any) {
    console.error('[API /api/catalogs/[id]/auto-sync PATCH] Error:', err);
    return NextResponse.json(
      { success: false, error: err.message || 'Failed to toggle auto sync' },
      { status: 500 }
    );
  }
}
