import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { NextResponse } from 'next/server';
import Database from 'better-sqlite3';
import path from 'path';

function getDb() {
  return new Database(path.join(process.cwd(), '..', 'data', 'bot.db'));
}

export async function GET(req: Request, { params }: { params: Promise<{ guildId: string }> }) {
  const session = await getServerSession(authOptions);
  if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { guildId } = await params;
  const url = new URL(req.url);
  const type = url.searchParams.get('type');

  const db = getDb();

  // Se pedir lista de advertências aplicadas
  if (type === 'applied') {
    const filter = url.searchParams.get('filter') || 'all';
    let query = 'SELECT * FROM warnings WHERE guild_id = ?';
    if (filter === 'active') query += ' AND active = 1';
    else if (filter === 'inactive') query += ' AND active = 0';
    query += ' ORDER BY created_at DESC';

    const warnings = db.prepare(query).all(guildId);
    db.close();
    return NextResponse.json({ warnings });
  }

  // Padrão: retorna configs e stats
  const configs = db.prepare('SELECT * FROM warning_configs WHERE guild_id = ? ORDER BY level ASC').all(guildId);
  const stats = {
    total: (db.prepare('SELECT COUNT(*) as c FROM warnings WHERE guild_id = ?').get(guildId) as any).c,
    active: (db.prepare('SELECT COUNT(*) as c FROM warnings WHERE guild_id = ? AND active = 1').get(guildId) as any).c,
  };
  db.close();
  return NextResponse.json({ configs, stats });
}

export async function POST(req: Request, { params }: { params: Promise<{ guildId: string }> }) {
  const session = await getServerSession(authOptions);
  if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { guildId } = await params;
  const { level, name, duration_days, role_id } = await req.json();

  const db = getDb();
  db.prepare('INSERT OR REPLACE INTO warning_configs (guild_id, level, name, duration_days, role_id) VALUES (?, ?, ?, ?, ?)').run(guildId, level, name, duration_days, role_id || null);
  db.close();

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

export async function PUT(req: Request, { params }: { params: Promise<{ guildId: string }> }) {
  const session = await getServerSession(authOptions);
  if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { guildId } = await params;
  const { id, reason, duration_days, active } = await req.json();

  const db = getDb();

  // Verificar se a advertência pertence ao servidor
  const warning = db.prepare('SELECT * FROM warnings WHERE id = ? AND guild_id = ?').get(id, guildId) as any;
  if (!warning) {
    db.close();
    return NextResponse.json({ error: 'Advertência não encontrada' }, { status: 404 });
  }

  // Construir update dinamicamente
  const updates: string[] = [];
  const values: any[] = [];

  if (reason !== undefined) {
    updates.push('reason = ?');
    values.push(reason);
  }

  if (duration_days !== undefined) {
    // Recalcular data de expiração baseado na data de criação
    const createdAt = new Date(warning.created_at);
    const newExpiry = new Date(createdAt.getTime() + (duration_days * 24 * 60 * 60 * 1000));
    updates.push('expires_at = ?');
    values.push(newExpiry.toISOString());
  }

  if (active !== undefined) {
    updates.push('active = ?');
    values.push(active ? 1 : 0);
  }

  if (updates.length > 0) {
    values.push(id);
    db.prepare(`UPDATE warnings SET ${updates.join(', ')} WHERE id = ?`).run(...values);
  }

  const updated = db.prepare('SELECT * FROM warnings WHERE id = ?').get(id);
  db.close();

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

export async function DELETE(req: Request, { params }: { params: Promise<{ guildId: string }> }) {
  const session = await getServerSession(authOptions);
  if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { guildId } = await params;
  const { id, type } = await req.json();

  const db = getDb();

  if (type === 'warning') {
    // Desativar advertência aplicada
    db.prepare('UPDATE warnings SET active = 0 WHERE id = ? AND guild_id = ?').run(id, guildId);
  } else {
    // Deletar config de nível
    db.prepare('DELETE FROM warning_configs WHERE id = ? AND guild_id = ?').run(id, guildId);
  }

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