import { NextRequest, NextResponse } from 'next/server';
import { requireAdmin } from '@/lib/admin-auth';
import { getDbClient } from '@/storage/database/local-db';

export async function GET(request: NextRequest) {
  const authError = await requireAdmin(request);
  if (authError) return authError;

  try {
    const client = await getDbClient();
    try {
      const data: Record<string, unknown[]> = {};

      const tables = [
        'profiles',
        'works',
        'credit_transactions',
        'orders',
        'user_api_keys',
        'system_api_configs',
        'payment_methods',
        'work_likes',
        'announcements',
      ];

      for (const table of tables) {
        try {
          const result = await client.query(`SELECT * FROM ${table} ORDER BY created_at ASC`);
          data[table] = result.rows || [];
        } catch {
          data[table] = [];
        }
      }

      try {
        const result = await client.query('SELECT * FROM site_config');
        data.site_config = result.rows || [];
      } catch { data.site_config = []; }

      try {
        const result = await client.query('SELECT * FROM site_stats');
        data.site_stats = result.rows || [];
      } catch { data.site_stats = []; }

      try {
        const result = await client.query('SELECT id, email, created_at, raw_user_meta_data, password_hash FROM auth.users');
        data.auth_users = result.rows || [];
      } catch { data.auth_users = []; }

      const exportData = {
        _meta: {
          version: '1.0',
          platform: 'miaojing',
          exported_at: new Date().toISOString(),
          tables: Object.keys(data),
          counts: Object.fromEntries(Object.entries(data).map(([k, v]) => [k, v.length])),
        },
        data,
      };

      return NextResponse.json(exportData);
    } finally {
      client.release();
    }
  } catch (err) {
    console.error('[data-export] Error:', err);
    return NextResponse.json({ error: err instanceof Error ? err.message : '导出失败' }, { status: 500 });
  }
}
