import { NextResponse } from 'next/server';
import { createServerClient } from '@supabase/ssr';
import { cookies } from 'next/headers';
import AdmZip from 'adm-zip';
import { Client } from 'pg';

function getPgClient() {
  const connectionString = process.env.DATABASE_URL || 'postgresql://postgres:postgres@localhost:54322/postgres';
  return new Client({
    connectionString,
    connectionTimeoutMillis: 10000,
  });
}

async function verifyAdmin() {
  const cookieStore = await cookies();
  const supabaseUrl = process.env.SUPABASE_URL || process.env.NEXT_PUBLIC_SUPABASE_URL || '';
  const supabase = createServerClient(
    supabaseUrl,
    process.env.SUPABASE_SERVICE_ROLE_KEY ?? '',
    {
      cookies: {
        getAll() {
          return cookieStore.getAll();
        },
        setAll(cookiesToSet) {
          try {
            cookiesToSet.forEach(({ name, value, options }) =>
              cookieStore.set(name, value, options)
            );
          } catch {
            // Ignored
          }
        },
      },
      cookieOptions: {
        name: "webshop-auth-token",
      },
    }
  );

  const { data: { user: authUser }, error: authError } = await supabase.auth.getUser();
  if (authError || !authUser) {
    return { errorResponse: NextResponse.json({ error: 'Not authenticated' }, { status: 401 }) };
  }
  const { data: user } = await supabase.from('users').select('role').eq('id', authUser.id).single();
  if (!user || user.role !== 'admin') {
    return { errorResponse: NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 }) };
  }
  return { success: true };
}

export async function GET() {
  const { errorResponse } = await verifyAdmin();
  if (errorResponse) return errorResponse;

  const client = getPgClient();
  await client.connect();

  try {
    const tables = [
      'categories',
      'products',
      'product_modules',
      'companies',
      'end_customers',
      'orders',
      'profiles',
      'users',
      'settings'
    ];

    const backupData: Record<string, any[]> = {};

    for (const table of tables) {
      const res = await client.query(`SELECT * FROM public.${table}`);
      backupData[table] = res.rows;
    }

    const zip = new AdmZip();
    const dataStr = JSON.stringify(backupData, null, 2);
    zip.addFile('db_backup.json', Buffer.from(dataStr, 'utf8'));
    const buffer = zip.toBuffer();

    return new Response(buffer, {
      headers: {
        'Content-Type': 'application/zip',
        'Content-Disposition': 'attachment; filename=db_backup.zip',
      },
    });
  } catch (err: any) {
    console.error('Backup export failed:', err);
    return NextResponse.json({ error: err.message }, { status: 500 });
  } finally {
    await client.end();
  }
}

export async function POST(request: Request) {
  const { errorResponse } = await verifyAdmin();
  if (errorResponse) return errorResponse;

  try {
    const formData = await request.formData();
    const file = formData.get('file') as File;
    if (!file) {
      return NextResponse.json({ error: 'No file provided' }, { status: 400 });
    }

    const arrayBuffer = await file.arrayBuffer();
    const zip = new AdmZip(Buffer.from(arrayBuffer));
    const zipEntries = zip.getEntries();
    const backupEntry = zipEntries.find(entry => entry.entryName === 'db_backup.json');
    if (!backupEntry) {
      return NextResponse.json({ error: 'Invalid backup file structure' }, { status: 400 });
    }

    const dataStr = backupEntry.getData().toString('utf8');
    const backupData = JSON.parse(dataStr);

    const client = getPgClient();
    await client.connect();

    try {
      await client.query('BEGIN');
      
      // Disable constraints
      await client.query("SET session_replication_role = 'replica'");

      const tables = [
        'categories',
        'products',
        'product_modules',
        'companies',
        'end_customers',
        'orders',
        'profiles',
        'users',
        'settings'
      ];

      // Delete existing rows in all tables
      for (const table of tables) {
        await client.query(`DELETE FROM public.${table}`);
      }

      // Insert backup data
      for (const table of tables) {
        const rows = backupData[table];
        if (!rows || rows.length === 0) continue;

        const columns = Object.keys(rows[0]);
        const columnNamesStr = columns.map(c => `"${c}"`).join(', ');

        for (const row of rows) {
          const values = columns.map(col => row[col]);
          const placeholders = columns.map((_, idx) => `$${idx + 1}`).join(', ');
          
          await client.query(
            `INSERT INTO public.${table} (${columnNamesStr}) VALUES (${placeholders})`,
            values
          );
        }
      }

      // Re-enable constraints
      await client.query("SET session_replication_role = 'origin'");
      await client.query('COMMIT');

      return NextResponse.json({ message: 'Database imported successfully.' });
    } catch (err: any) {
      await client.query('ROLLBACK');
      console.error('Backup import failed:', err);
      return NextResponse.json({ error: err.message }, { status: 500 });
    } finally {
      await client.end();
    }
  } catch (err: any) {
    console.error('Backup import request processing failed:', err);
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
