import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth/authOptions';
import { query } from '@/lib/db-postgres';
import { v4 as uuidv4 } from 'uuid';

export async function GET(request: Request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'No authorization token provided' }, { status: 401 });
    }

    const rows = await query<{ data: any }>(
      `SELECT data FROM fs_users WHERE data->>'email' = $1 LIMIT 1`,
      [session.user.email]
    );

    if (rows.length > 0 && rows[0].data?.apiKey) {
      return NextResponse.json({ apiKey: rows[0].data.apiKey });
    }

    // Generate new API key and store it
    const apiKey = `vibn_${uuidv4().replace(/-/g, '')}`;

    await query(
      `UPDATE fs_users
       SET data = data || $1::jsonb, updated_at = NOW()
       WHERE data->>'email' = $2`,
      [JSON.stringify({ apiKey, apiKeyCreatedAt: new Date().toISOString() }), session.user.email]
    );

    return NextResponse.json({ apiKey, isNew: true });
  } catch (error) {
    console.error('[API] Error getting/creating API key:', error);
    return NextResponse.json(
      { error: 'Failed to get API key', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}
