import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { writeFile, mkdir, unlink, chmod } from 'fs/promises';
import { join } from 'path';
import { existsSync } from 'fs';

async function checkAuth() {
  const cookieStore = await cookies();
  const auth = cookieStore.get('admin-auth');
  return auth?.value === 'authenticated';
}

export async function POST(request: NextRequest) {
  if (!(await checkAuth())) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const formData = await request.formData();
    const file = formData.get('file') as File;
    const type = formData.get('type') as string; // 'partner', 'site', or 'favicon'
    const oldPath = formData.get('oldPath') as string | null; // Old file path to delete

    if (!file) {
      return NextResponse.json({ error: 'No file provided' }, { status: 400 });
    }

    const bytes = await file.arrayBuffer();
    const buffer = Buffer.from(bytes);

    // Delete old file if provided
    if (oldPath) {
      try {
        const oldFilePath = join(process.cwd(), 'public', oldPath.replace(/^\//, ''));
        if (existsSync(oldFilePath)) {
          await unlink(oldFilePath);
        }
      } catch (error) {
        // Ignore errors when deleting old file (might not exist)
        console.log('Could not delete old file:', error);
      }
    }

    // Determine upload directory
    let uploadDir: string;
    let filename: string;
    let publicPath: string;

    if (type === 'partner') {
      uploadDir = 'public/logos';
      const timestamp = Date.now();
      const baseName = file.name.replace(/\s+/g, '-').toLowerCase();
      const extension = baseName.split('.').pop();
      const nameWithoutExt = baseName.replace(/\.[^/.]+$/, '');
      filename = `${nameWithoutExt}-${timestamp}.${extension}`;
      publicPath = `/logos/${filename}`;
    } else if (type === 'favicon') {
      uploadDir = 'public';
      const extension = file.name.split('.').pop();
      filename = `favicon.${extension}`;
      publicPath = `/${filename}`;
      
      // Delete old favicon files (favicon.ico, favicon.png, etc.)
      try {
        const faviconExtensions = ['ico', 'png', 'svg', 'jpg', 'jpeg'];
        for (const ext of faviconExtensions) {
          const oldFaviconPath = join(process.cwd(), 'public', `favicon.${ext}`);
          if (existsSync(oldFaviconPath)) {
            await unlink(oldFaviconPath);
          }
        }
      } catch (error) {
        console.log('Could not delete old favicon files:', error);
      }
    } else {
      // site logo
      uploadDir = 'public';
      const timestamp = Date.now();
      const extension = file.name.split('.').pop();
      filename = `logo-${timestamp}.${extension}`;
      publicPath = `/${filename}`;
    }

    const uploadPath = join(process.cwd(), uploadDir);

    // Ensure directory exists with proper permissions (755)
    await mkdir(uploadPath, { recursive: true, mode: 0o755 });
    
    // Set directory permissions explicitly (755 = rwxr-xr-x)
    try {
      await chmod(uploadPath, 0o755);
    } catch (error) {
      // Ignore chmod errors on some systems
      console.log('Could not set directory permissions:', error);
    }

    const filePath = join(uploadPath, filename);

    // Write file with proper permissions (644 = rw-r--r--)
    await writeFile(filePath, buffer, { mode: 0o644 });
    
    // Set file permissions explicitly (644 = rw-r--r--)
    try {
      await chmod(filePath, 0o644);
    } catch (error) {
      // Ignore chmod errors on some systems
      console.log('Could not set file permissions:', error);
    }

    return NextResponse.json({ 
      success: true, 
      path: publicPath,
      filename: filename
    });
  } catch (error: any) {
    console.error('Upload error:', error);
    
    // Provide more specific error messages for permission issues
    if (error.code === 'EACCES' || error.code === 'EPERM') {
      return NextResponse.json(
        { 
          error: 'Permission denied. Please ensure the server has write permissions for the public directory.',
          details: error.message 
        },
        { status: 403 }
      );
    }
    
    if (error.code === 'ENOENT') {
      return NextResponse.json(
        { 
          error: 'Directory not found. Please ensure the public directory exists.',
          details: error.message 
        },
        { status: 404 }
      );
    }
    
    return NextResponse.json(
      { 
        error: 'Failed to upload file',
        details: error.message || 'Unknown error'
      },
      { status: 500 }
    );
  }
}

