/**
 * OAuth provider repository — CRUD for auth_providers container.
 */

import { getCollection } from '../../../lib/datastore.js';
import type { AuthProviderDoc } from '../types.js';

function providersCollection() {
  return getCollection<AuthProviderDoc>('auth_providers', '/userId');
}

export async function linkProvider(doc: AuthProviderDoc): Promise<AuthProviderDoc> {
  return providersCollection().create(doc);
}

export async function getByUserAndProvider(
  userId: string,
  provider: string
): Promise<AuthProviderDoc | null> {
  const id = `${userId}:${provider}`;
  try {
    return await providersCollection().findById(id, userId);
  } catch {
    return null;
  }
}

export async function getByProviderUserId(
  provider: string,
  providerUserId: string
): Promise<AuthProviderDoc | null> {
  return providersCollection().findOne({
    filter: { provider, providerUserId },
  });
}

export async function listByUser(userId: string): Promise<AuthProviderDoc[]> {
  return providersCollection().findMany({
    filter: { userId },
  });
}

export async function updateLastUsed(userId: string, provider: string): Promise<void> {
  const id = `${userId}:${provider}`;
  try {
    await providersCollection().update(id, userId, {
      lastUsedAt: new Date().toISOString(),
    } as Partial<AuthProviderDoc>);
  } catch {
    // best-effort
  }
}

export async function unlinkProvider(userId: string, provider: string): Promise<boolean> {
  const id = `${userId}:${provider}`;
  try {
    await providersCollection().delete(id, userId);
    return true;
  } catch {
    return false;
  }
}
