import { NextRequest, NextResponse } from 'next/server';
import { getAdminSession } from '@/lib/auth/adminAuth';
import { db } from '@/db/client';
import { normalizeAssetUrl } from '@/lib/utils/asset';

export const dynamic = 'force-dynamic';

/**
 * GET: Retrieve branding settings for the admin panel
 */
export async function GET(req: NextRequest) {
  try {
    const session = await getAdminSession(req);
    if (!session.authenticated || !session.user) {
      return NextResponse.json({ error: 'Authentication required' }, { status: 401 });
    }

    const branding = await db.getSystemBranding();
    const isSuperAdmin = session.user.role === 'super_admin';

    return NextResponse.json({
      success: true,
      branding: {
        appName: branding.app_name,
        logoUrl: normalizeAssetUrl(branding.logo_url || '/images/logo.png'),
        faviconUrl: normalizeAssetUrl(branding.favicon_url || '/favicon.ico'),
        updatedAt: branding.updated_at,
        updatedBy: branding.updated_by,
      },
      isSuperAdmin,
    });
  } catch (error: any) {
    console.error('Error fetching admin branding:', error);
    return NextResponse.json({ error: error?.message || 'Failed to fetch branding' }, { status: 500 });
  }
}

/**
 * POST: Update global branding (Super Admin only)
 */
export async function POST(req: NextRequest) {
  try {
    const session = await getAdminSession(req);
    if (!session.authenticated || !session.user) {
      return NextResponse.json({ error: 'Authentication required' }, { status: 401 });
    }

    // Role-based Access Control: Super Admin only
    if (session.user.role !== 'super_admin') {
      return NextResponse.json(
        { error: 'Access denied: Only Super Administrators can modify global application branding.' },
        { status: 403 }
      );
    }

    const body = await req.json();
    const { appName, logoUrl, faviconUrl } = body;

    // Validate Application Name
    if (appName !== undefined) {
      if (typeof appName !== 'string' || appName.trim().length < 2) {
        return NextResponse.json(
          { error: 'Application name must be at least 2 characters long.' },
          { status: 400 }
        );
      }
      if (appName.trim().length > 100) {
        return NextResponse.json(
          { error: 'Application name cannot exceed 100 characters.' },
          { status: 400 }
        );
      }
    }

    // Sanitize URLs if provided
    let cleanLogoUrl = logoUrl;
    if (logoUrl !== undefined && logoUrl !== null) {
      if (typeof logoUrl !== 'string' || (!logoUrl.startsWith('/') && !logoUrl.startsWith('http://') && !logoUrl.startsWith('https://') && !logoUrl.startsWith('data:image/'))) {
        return NextResponse.json({ error: 'Invalid logo URL format.' }, { status: 400 });
      }
      cleanLogoUrl = logoUrl.trim();
    }

    let cleanFaviconUrl = faviconUrl;
    if (faviconUrl !== undefined && faviconUrl !== null) {
      if (typeof faviconUrl !== 'string' || (!faviconUrl.startsWith('/') && !faviconUrl.startsWith('http://') && !faviconUrl.startsWith('https://') && !faviconUrl.startsWith('data:image/'))) {
        return NextResponse.json({ error: 'Invalid favicon URL format.' }, { status: 400 });
      }
      cleanFaviconUrl = faviconUrl.trim();
    }

    const updated = await db.updateSystemBranding(
      {
        app_name: appName !== undefined ? appName.trim() : undefined,
        logo_url: cleanLogoUrl,
        favicon_url: cleanFaviconUrl,
      },
      `${session.user.name} (${session.user.email})`
    );

    // Record activity log for audit trail
    try {
      await db.createStoreActivityLog({
        shop_id: 'saas_admin',
        shopify_domain: 'system.global',
        action: 'branding_updated',
        actor: session.user.name,
        description: `Updated application branding: "${updated.app_name}" (Logo: ${updated.logo_url ? 'custom' : 'none'}, Favicon: ${updated.favicon_url ? 'custom' : 'none'})`,
        metadata: {
          app_name: updated.app_name,
          logo_url: updated.logo_url,
          favicon_url: updated.favicon_url,
          admin_id: session.user.id,
          admin_email: session.user.email,
        },
      });
    } catch {
      // ignore log failure
    }

    return NextResponse.json({
      success: true,
      message: 'Branding settings updated successfully.',
      branding: {
        appName: updated.app_name,
        logoUrl: normalizeAssetUrl(updated.logo_url || '/images/logo.png'),
        faviconUrl: normalizeAssetUrl(updated.favicon_url || '/favicon.ico'),
        updatedAt: updated.updated_at,
        updatedBy: updated.updated_by,
      },
    });
  } catch (error: any) {
    console.error('Error saving admin branding:', error);
    return NextResponse.json({ error: error?.message || 'Failed to save branding' }, { status: 500 });
  }
}
