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

/** Returns the stored GitHub access token for the current user — used by the engine clone step. */
export async function GET(request: NextRequest) {
  const session = await getSession(request.cookies.get('scriba.access_token')?.value);
  if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

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

  if (!account?.accessToken) {
    return NextResponse.json({ token: null });
  }

  return NextResponse.json({ token: account.accessToken });
}

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 });
  }

  // Validate PAT by fetching GitHub user info
  const res = await fetch('https://api.github.com/user', {
    headers: { Authorization: `Bearer ${pat}`, Accept: 'application/vnd.github+json' },
  });
  if (!res.ok) {
    return NextResponse.json(
      { error: 'Invalid token — GitHub rejected it. Make sure it has the "repo" scope.' },
      { status: 400 }
    );
  }
  const ghUser = await res.json();

  // Upsert into accounts table (same as OAuth flow)
  const existing = await db.query.accounts.findFirst({
    where: and(
      eq(schema.accounts.userId, session.user.id),
      eq(schema.accounts.providerId, 'github')
    ),
  });

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

  return NextResponse.json({
    connected: true,
    login: ghUser.login,
    name: ghUser.name,
    avatar: ghUser.avatar_url,
    url: ghUser.html_url,
  });
}
