import { NextResponse } from 'next/server';
import { authSession } from "@/lib/auth/session-server";
import { query } from '@/lib/db-postgres';

export async function POST(request: Request) {
  try {
    const session = await authSession();
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { accessToken, githubUser } = await request.json();
    if (!accessToken || !githubUser) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    await query(
      `UPDATE fs_users
       SET data = data || $1::jsonb, updated_at = NOW()
       WHERE data->>'email' = $2`,
      [
        JSON.stringify({
          githubConnected: true,
          githubUserId: githubUser.id,
          githubUsername: githubUser.login,
          githubName: githubUser.name,
          githubEmail: githubUser.email,
          githubAvatarUrl: githubUser.avatar_url,
          githubAccessToken: accessToken,
          githubConnectedAt: new Date().toISOString(),
        }),
        session.user.email,
      ]
    );

    return NextResponse.json({ success: true, githubUsername: githubUser.login });
  } catch (error) {
    console.error('[GitHub Connect] Error:', error);
    return NextResponse.json({ error: 'Failed to store GitHub connection' }, { status: 500 });
  }
}

export async function GET(request: Request) {
  try {
    const session = await authSession();
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { 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?.githubConnected) {
      return NextResponse.json({ connected: false });
    }

    const d = rows[0].data;
    return NextResponse.json({
      connected: true,
      githubUsername: d.githubUsername,
      githubName: d.githubName,
      githubAvatarUrl: d.githubAvatarUrl,
      connectedAt: d.githubConnectedAt,
    });
  } catch (error) {
    console.error('[GitHub Connect] Error:', error);
    return NextResponse.json({ error: 'Failed to fetch GitHub connection' }, { status: 500 });
  }
}

export async function DELETE(request: Request) {
  try {
    const session = await authSession();
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    await query(
      `UPDATE fs_users
       SET data = data - 'githubConnected' - 'githubUserId' - 'githubUsername'
                      - 'githubName' - 'githubEmail' - 'githubAvatarUrl'
                      - 'githubAccessToken' - 'githubConnectedAt',
           updated_at = NOW()
       WHERE data->>'email' = $1`,
      [session.user.email]
    );

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('[GitHub Disconnect] Error:', error);
    return NextResponse.json({ error: 'Failed to disconnect GitHub' }, { status: 500 });
  }
}
