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

export async function GET(request: NextRequest) {
  const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
  const { searchParams } = new URL(request.url);
  const code = searchParams.get('code');
  const state = searchParams.get('state');
  const error = searchParams.get('error');

  if (error) return NextResponse.redirect(`${appUrl}/?gitlab_error=${error}`);
  if (!code || !state) return NextResponse.redirect(`${appUrl}/?gitlab_error=missing_params`);

  const session = await getSession(request.cookies.get('scriba.access_token')?.value);
  if (!session || session.user.id !== state) return NextResponse.redirect(`${appUrl}/?gitlab_error=invalid_state`);

  const tokenRes = await fetch('https://gitlab.com/oauth/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      client_id: process.env.GITLAB_CLIENT_ID,
      client_secret: process.env.GITLAB_CLIENT_SECRET,
      code,
      grant_type: 'authorization_code',
      redirect_uri: `${appUrl}/api/auth/gitlab/callback`,
    }),
  });

  const tokenData = await tokenRes.json();
  if (!tokenData.access_token) return NextResponse.redirect(`${appUrl}/?gitlab_error=token_exchange_failed`);

  const userRes = await fetch('https://gitlab.com/api/v4/user', {
    headers: { Authorization: `Bearer ${tokenData.access_token}` },
  });
  const glUser = await userRes.json();

  const existing = await db.query.accounts.findFirst({
    where: and(eq(schema.accounts.userId, session.user.id), eq(schema.accounts.providerId, 'gitlab')),
  });

  if (existing) {
    await db.update(schema.accounts)
      .set({ accessToken: tokenData.access_token, accountId: String(glUser.id), updatedAt: new Date() })
      .where(eq(schema.accounts.id, existing.id));
  } else {
    await db.insert(schema.accounts).values({
      id: `gitlab-${session.user.id}`,
      userId: session.user.id,
      providerId: 'gitlab',
      accountId: String(glUser.id),
      accessToken: tokenData.access_token,
    });
  }

  return NextResponse.redirect(`${appUrl}/?gitlab_connected=1`);
}
