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 POST(request: NextRequest) {
  const session = await getSession(request.cookies.get('scriba.access_token')?.value);
  if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const body = await request.json().catch(() => ({}));
  const pat = typeof body.token === 'string' ? body.token.trim() : '';
  if (!pat) return NextResponse.json({ error: 'Token is required' }, { status: 400 });

  const res = await fetch('https://gitlab.com/api/v4/user', {
    headers: { 'PRIVATE-TOKEN': pat },
  });
  if (!res.ok) {
    return NextResponse.json(
      { error: 'Invalid token — GitLab rejected it. Make sure it has api or read_api scope.' },
      { status: 400 }
    );
  }
  const glUser = await res.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: pat, 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: pat,
    });
  }

  return NextResponse.json({
    connected: true,
    login: glUser.username,
    name: glUser.name,
    avatar: glUser.avatar_url,
    url: glUser.web_url,
  });
}
