import { db, schema } from '@/lib/db';
import { eq, and } from 'drizzle-orm';

export function detectVcsProvider(repoUrl: string): string | null {
  if (repoUrl.includes('github.com')) return 'github';
  if (repoUrl.includes('gitlab.com')) return 'gitlab';
  if (repoUrl.includes('bitbucket.org')) return 'bitbucket';
  if (repoUrl.includes('dev.azure.com') || repoUrl.includes('visualstudio.com')) return 'azure';
  return null;
}

export async function resolveVcsAccessToken(userId: string, repoUrl: string): Promise<string | undefined> {
  const providerId = detectVcsProvider(repoUrl);
  if (!providerId) return undefined;

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

  return account?.accessToken ?? undefined;
}

export function injectTokenIntoRepoUrl(repoUrl: string, token: string, provider: string): string {
  try {
    const u = new URL(repoUrl);
    if (provider === 'github') {
      u.username = 'x-access-token';
      u.password = token;
    } else if (provider === 'gitlab') {
      u.username = 'oauth2';
      u.password = token;
    } else if (provider === 'bitbucket') {
      u.username = 'x-token-auth';
      u.password = token;
    } else if (provider === 'azure') {
      u.username = token;
      u.password = '';
    }
    return u.toString();
  } catch {
    return repoUrl;
  }
}
