import { NextRequest, NextResponse } from 'next/server';
import { dbHelpers } from '@/lib/db';
import { getSession } from '@/lib/auth';
import { LOG_LEVELS } from '@/lib/schema';

async function authorizeProject(request: NextRequest, projectId: string) {
  const accessToken = request.cookies.get('scriba.access_token')?.value;
  const session = await getSession(accessToken);
  if (!session) {
    return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
  }
  const project = await dbHelpers.getProject(projectId);
  if (!project) {
    return { error: NextResponse.json({ error: 'Conversion not found' }, { status: 404 }) };
  }
  if (project.userId !== session.user.id) {
    return { error: NextResponse.json({ error: 'Forbidden' }, { status: 403 }) };
  }
  return { session, project };
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const auth = await authorizeProject(request, id);
    if ('error' in auth) return auth.error;

    const logs = await dbHelpers.getProjectLogs(id);
    return NextResponse.json({ logs });
  } catch (error) {
    console.error('Error fetching logs:', error);
    return NextResponse.json({ error: 'Failed to fetch logs' }, { status: 500 });
  }
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const auth = await authorizeProject(request, id);
    if ('error' in auth) return auth.error;

    const body = await request.json();
    const { time, level, message } = body;
    if (!time || !level || !message) {
      return NextResponse.json({ error: 'time, level, and message are required' }, { status: 400 });
    }
    if (!(LOG_LEVELS as readonly string[]).includes(level)) {
      return NextResponse.json(
        { error: `level must be one of: ${LOG_LEVELS.join(', ')}` },
        { status: 400 },
      );
    }

    const log = await dbHelpers.saveLog(id, time, level, message);
    return NextResponse.json({ log });
  } catch (error) {
    console.error('Error saving log:', error);
    return NextResponse.json({ error: 'Failed to save log' }, { status: 500 });
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const auth = await authorizeProject(request, id);
    if ('error' in auth) return auth.error;

    await dbHelpers.clearProjectLogs(id);
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error clearing logs:', error);
    return NextResponse.json({ error: 'Failed to clear logs' }, { status: 500 });
  }
}
