import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/auth';
import { pgSaveSettings } from '@/lib/postgres/data-access';

export async function POST(request: NextRequest) {
  try {
    const session = await getSession();
    if (!session?.user || session.user.role !== 'admin') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const { storeName, storeDescription, storeContactPhone, storeLogoUrl, storeModuleEnabled } = body;

    const patch: Record<string, unknown> = {};
    if (storeModuleEnabled !== undefined) patch.storeModuleEnabled = storeModuleEnabled === true || storeModuleEnabled === 'true';

    if (storeName !== undefined) patch.storeName = String(storeName || '').trim().slice(0, 100);
    if (storeDescription !== undefined) patch.storeDescription = String(storeDescription || '').trim().slice(0, 300);
    if (storeContactPhone !== undefined) patch.storeContactPhone = String(storeContactPhone || '').trim().replace(/[^\d+\s-]/g, '').slice(0, 20);
    if (storeLogoUrl !== undefined) {
      const url = String(storeLogoUrl || '').trim();
      if (url && !url.startsWith('https://')) {
        return NextResponse.json({ error: 'رابط الشعار يجب أن يبدأ بـ https://' }, { status: 400 });
      }
      patch.storeLogoUrl = url.slice(0, 500);
    }

    await pgSaveSettings(patch);

    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error('[settings/store] POST error:', error);
    return NextResponse.json({ error: error?.message || 'Internal server error' }, { status: 500 });
  }
}
