import { NextResponse } from 'next/server';
import { getDbClient } from '@/storage/database/local-db';
import { listSystemApis } from '@/lib/server-api-config';

function mapProvider(row: Record<string, unknown>) {
  return {
    id: String(row.id),
    name: String(row.name || ''),
    defaultApiUrl: String(row.default_api_url || ''),
    defaultModel: String(row.default_model || ''),
    type: String(row.type || 'image'),
    website: (row.website as string | null) || null,
    isActive: row.is_active !== false,
    sortOrder: Number(row.sort_order || 0),
  };
}

function mapRecommendation(row: Record<string, unknown>) {
  return {
    id: String(row.id),
    modelName: String(row.model_name || ''),
    displayName: String(row.display_name || row.model_name || ''),
    type: String(row.type || 'image'),
    providerId: (row.provider_id as string | null) || null,
    isActive: row.is_active !== false,
    sortOrder: Number(row.sort_order || 0),
  };
}

export async function GET() {
  try {
    const client = await getDbClient();
    try {
      const providers = await client.query(
        `SELECT id, name, default_api_url, default_model, type, website, is_active, sort_order
         FROM api_providers
         WHERE is_active = true
         ORDER BY sort_order ASC, name ASC`
      );
      const recommendations = await client.query(
        `SELECT id, model_name, display_name, type, provider_id, is_active, sort_order
         FROM model_recommendations
         WHERE is_active = true
         ORDER BY type ASC, sort_order ASC, model_name ASC`
      );

      return NextResponse.json({
        providers: providers.rows.map(mapProvider),
        recommendations: recommendations.rows.map(mapRecommendation),
        systemApis: await listSystemApis(false),
      });
    } finally {
      client.release();
    }
  } catch (err) {
    console.error('[model-config] GET error:', err);
    return NextResponse.json({ providers: [], recommendations: [] });
  }
}
