import { NextRequest, NextResponse } from 'next/server';
import { db, schema } from '@/lib/db';
import { eq, and, gt, ne } from 'drizzle-orm';
import { getSession } from '@/lib/auth';

export async function GET(request: NextRequest) {
  try {
    const accessToken = request.cookies.get('scriba.access_token')?.value;
    const session = await getSession(accessToken);
    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const sessions = await db.query.sessions.findMany({
      where: and(
        eq(schema.sessions.userId, session.user.id),
        gt(schema.sessions.expiresAt, new Date())
      ),
    });

    return NextResponse.json({
      sessions: sessions.map(s => ({
        id: s.id,
        current: s.id === session.session.id,
        ipAddress: s.ipAddress || 'Unknown',
        userAgent: s.userAgent || 'Unknown',
        createdAt: s.createdAt?.toISOString(),
        expiresAt: s.expiresAt.toISOString(),
      })),
    });
  } catch (error) {
    return NextResponse.json({ error: 'Failed to fetch sessions' }, { status: 500 });
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const accessToken = request.cookies.get('scriba.access_token')?.value;
    const session = await getSession(accessToken);
    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json().catch(() => ({})) as { targetSessionId?: string; revokeAll?: boolean };

    if (body.revokeAll) {
      // Delete all sessions belonging to this user except the current one
      await db.delete(schema.sessions).where(
        and(
          eq(schema.sessions.userId, session.user.id),
          ne(schema.sessions.id, session.session.id),
        )
      );
      return NextResponse.json({ success: true, revokedAll: true });
    }

    const { targetSessionId } = body;
    if (!targetSessionId || targetSessionId === session.session.id) {
      return NextResponse.json({ error: 'Cannot revoke current session' }, { status: 400 });
    }

    await db.delete(schema.sessions).where(
      and(
        eq(schema.sessions.id, targetSessionId),
        eq(schema.sessions.userId, session.user.id)
      )
    );

    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json({ error: 'Failed to revoke session' }, { status: 500 });
  }
}
