import { NextRequest, NextResponse } from 'next/server';
import path from 'path';
import fs from 'fs';
import crypto from 'crypto';
import { getAdminSession } from '@/lib/auth/adminAuth';

export const dynamic = 'force-dynamic';

const MAX_LOGO_SIZE = 2 * 1024 * 1024; // 2MB
const MAX_FAVICON_SIZE = 512 * 1024; // 512KB

const ALLOWED_LOGO_MIMES = [
  'image/png',
  'image/jpeg',
  'image/jpg',
  'image/webp',
  'image/svg+xml',
];

const ALLOWED_FAVICON_MIMES = [
  'image/x-icon',
  'image/vnd.microsoft.icon',
  'image/png',
  'image/svg+xml',
  'image/jpeg',
  'image/jpg',
  'image/webp',
];

const ALLOWED_LOGO_EXTS = ['.png', '.jpg', '.jpeg', '.webp', '.svg'];
const ALLOWED_FAVICON_EXTS = ['.ico', '.png', '.svg', '.webp', '.jpg', '.jpeg'];

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 });
    }

    if (session.user.role !== 'super_admin') {
      return NextResponse.json(
        { error: 'Access denied: Only Super Administrators can upload branding assets.' },
        { status: 403 }
      );
    }

    const formData = await req.formData();
    const file = formData.get('file') as File | null;
    const type = ((formData.get('type') as string) || 'logo').toLowerCase();

    if (!file || typeof file.arrayBuffer !== 'function') {
      return NextResponse.json({ error: 'No file provided or invalid upload.' }, { status: 400 });
    }

    const isFavicon = type === 'favicon';
    const maxSize = isFavicon ? MAX_FAVICON_SIZE : MAX_LOGO_SIZE;
    const allowedMimes = isFavicon ? ALLOWED_FAVICON_MIMES : ALLOWED_LOGO_MIMES;
    const allowedExts = isFavicon ? ALLOWED_FAVICON_EXTS : ALLOWED_LOGO_EXTS;

    // 1. File Size Validation
    if (file.size > maxSize) {
      const limitLabel = isFavicon ? '512KB' : '2MB';
      return NextResponse.json(
        { error: `File size exceeds the maximum allowed limit of ${limitLabel}.` },
        { status: 400 }
      );
    }

    // 2. MIME Type Validation
    const mime = file.type ? file.type.toLowerCase() : '';
    if (mime && !allowedMimes.includes(mime)) {
      return NextResponse.json(
        { error: `Unsupported file format (${mime}). Allowed formats: ${allowedExts.join(', ')}.` },
        { status: 400 }
      );
    }

    // 3. Extension Validation
    const origExt = path.extname(file.name || '').toLowerCase();
    const cleanExt = allowedExts.includes(origExt) ? origExt : isFavicon ? '.ico' : '.png';

    // 4. Ensure target directory exists
    const uploadDir = path.join(process.cwd(), 'public', 'uploads', 'branding');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }

    // 5. Generate safe unique filename
    const uniqueId = crypto.randomBytes(6).toString('hex');
    const safeFilename = `${isFavicon ? 'favicon' : 'logo'}_${Date.now()}_${uniqueId}${cleanExt}`;
    const destinationPath = path.join(uploadDir, safeFilename);

    // 6. Write file buffer
    const arrayBuffer = await file.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer);

    // Basic SVG sanitization to prevent script execution if SVG
    if (cleanExt === '.svg') {
      const svgText = buffer.toString('utf8');
      if (/<script/i.test(svgText) || /javascript:/i.test(svgText) || /onload=/i.test(svgText) || /onerror=/i.test(svgText)) {
        return NextResponse.json({ error: 'SVG contains potentially unsafe script content.' }, { status: 400 });
      }
    }

    await fs.promises.writeFile(destinationPath, buffer);

    const publicUrl = `/uploads/branding/${safeFilename}`;

    return NextResponse.json({
      success: true,
      message: `${isFavicon ? 'Favicon' : 'Logo'} uploaded successfully.`,
      url: publicUrl,
      filename: safeFilename,
      size: file.size,
      mime: mime || 'image/' + cleanExt.replace('.', ''),
    });
  } catch (error: any) {
    console.error('Error handling asset upload:', error);
    return NextResponse.json({ error: error?.message || 'File upload failed' }, { status: 500 });
  }
}
