import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { pingOllama, getOllamaModels } from '@/lib/ai/hybridRouter';

// ─── GET — AI Console settings ────────────────────────────────────────────────
export async function GET(request: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const { data: profile } = await supabase.from('user_profiles').select('role').eq('id', user.id).single();
    if (!['administrator', 'admin'].includes(profile?.role || '')) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const { searchParams } = new URL(request.url);
    const action = searchParams.get('action');

    if (action === 'test_connection') {
      const status = await pingOllama();
      return NextResponse.json(status);
    }

    if (action === 'models') {
      const models = await getOllamaModels();
      return NextResponse.json({ models });
    }

    // Load settings from DB
    const { data: settings } = await supabase
      .from('ai_console_settings')
      .select('*')
      .limit(1)
      .single();

    return NextResponse.json({
      settings: settings || {
        ollama_endpoint: process.env.OLLAMA_ENDPOINT || '',
        ollama_model_default: process.env.OLLAMA_MODEL_DEFAULT || '',
        ollama_model_translation: process.env.OLLAMA_MODEL_TRANSLATION || '',
        ollama_model_background: process.env.OLLAMA_MODEL_BACKGROUND || '',
        auto_failover: true,
        failover_timeout_seconds: 8,
        default_site_id: 1,
        default_pen_name_bb: 'Michael Strand',
        default_pen_name_av: 'Rex Chandler',
        save_session_history: true,
        history_retention_days: 30,
        streaming_enabled: true,
        background_use_local: true,
        background_timeout_seconds: 120,
        priority_queue_enabled: true,
      },
    });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}

// ─── POST — save settings ─────────────────────────────────────────────────────
export async function POST(request: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const { data: profile } = await supabase.from('user_profiles').select('role').eq('id', user.id).single();
    if (!['administrator', 'admin'].includes(profile?.role || '')) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const body = await request.json();
    const { action } = body;

    if (action === 'save_settings') {
      const {
        ollama_endpoint, ollama_model_default, ollama_model_translation,
        ollama_model_background, auto_failover, failover_timeout_seconds,
        default_site_id, default_pen_name_bb, default_pen_name_av,
        save_session_history, history_retention_days, streaming_enabled,
        background_use_local, background_timeout_seconds, priority_queue_enabled,
      } = body;

      // Update env-level settings (stored in DB for UI display; actual env vars set separately)
      const { data: existing } = await supabase.from('ai_console_settings').select('id').limit(1).single();

      const settingsData = {
        ollama_endpoint: ollama_endpoint || '',
        ollama_model_default: ollama_model_default || '',
        ollama_model_translation: ollama_model_translation || '',
        ollama_model_background: ollama_model_background || '',
        auto_failover: auto_failover !== false,
        failover_timeout_seconds: failover_timeout_seconds || 8,
        default_site_id: default_site_id || 1,
        default_pen_name_bb: default_pen_name_bb || 'Michael Strand',
        default_pen_name_av: default_pen_name_av || 'Rex Chandler',
        save_session_history: save_session_history !== false,
        history_retention_days: history_retention_days || 30,
        streaming_enabled: streaming_enabled !== false,
        background_use_local: background_use_local !== false,
        background_timeout_seconds: background_timeout_seconds || 120,
        priority_queue_enabled: priority_queue_enabled !== false,
        updated_at: new Date().toISOString(),
      };

      if (existing?.id) {
        await supabase.from('ai_console_settings').update(settingsData).eq('id', existing.id);
      } else {
        await supabase.from('ai_console_settings').insert(settingsData);
      }

      return NextResponse.json({ success: true });
    }

    // Sessions management
    if (action === 'create_session') {
      const { site_id, pen_name, first_message } = body;
      const { data: session } = await supabase
        .from('ai_console_sessions')
        .insert({
          user_id: user.id,
          site_id: site_id || 1,
          pen_name: pen_name || null,
          first_message_preview: (first_message || '').slice(0, 100),
          provider_used: 'anthropic',
          model_used: 'claude-sonnet-4-20250514',
          last_message_at: new Date().toISOString(),
        })
        .select()
        .single();
      return NextResponse.json({ session });
    }

    if (action === 'save_message') {
      const { session_id, role, content, provider } = body;
      await supabase.from('ai_console_messages').insert({
        session_id,
        role,
        content,
        provider_used: provider || null,
        created_at: new Date().toISOString(),
      });
      return NextResponse.json({ success: true });
    }

    if (action === 'delete_session') {
      const { session_id } = body;
      await supabase.from('ai_console_messages').delete().eq('session_id', session_id);
      await supabase.from('ai_console_sessions').delete().eq('id', session_id).eq('user_id', user.id);
      return NextResponse.json({ success: true });
    }

    if (action === 'save_draft') {
      const { title, content, pen_name, site_id } = body;
      const slug = (title || 'ai-draft')
        .toLowerCase()
        .replace(/[^a-z0-9\s-]/g, '')
        .replace(/\s+/g, '-')
        .trim()
        .slice(0, 80) + '-draft-' + Date.now();

      const { data: draft } = await supabase
        .from('native_articles')
        .insert({
          slug,
          title: title || 'AI Draft',
          content: content || '',
          excerpt: (content || '').replace(/<[^>]+>/g, '').slice(0, 200),
          author_name: pen_name || 'Michael Strand',
          status: 'draft',
          site_id: site_id || 1,
        })
        .select('id, slug')
        .single();

      return NextResponse.json({ draft });
    }

    return NextResponse.json({ error: 'Unknown action' }, { status: 400 });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}

// ─── GET sessions list ────────────────────────────────────────────────────────
export async function PATCH(request: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const { searchParams } = new URL(request.url);
    const action = searchParams.get('action') || (await request.json().catch(() => ({}))).action;

    // Get recent sessions
    const { data: sessions } = await supabase
      .from('ai_console_sessions')
      .select('id, site_id, pen_name, first_message_preview, provider_used, model_used, last_message_at, created_at')
      .eq('user_id', user.id)
      .order('last_message_at', { ascending: false })
      .limit(20);

    return NextResponse.json({ sessions: sessions || [] });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
