/**
 * Enterprise IdP repository — CRUD for auth_enterprise_idps container.
 */

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

function idpCollection() {
  return getCollection<EnterpriseIdpDoc>('auth_enterprise_idps', '/orgId');
}

export async function create(doc: EnterpriseIdpDoc): Promise<EnterpriseIdpDoc> {
  return idpCollection().create(doc);
}

export async function getById(id: string, orgId: string): Promise<EnterpriseIdpDoc | null> {
  try {
    return await idpCollection().findById(id, orgId);
  } catch {
    return null;
  }
}

export async function listByOrg(orgId: string): Promise<EnterpriseIdpDoc[]> {
  return idpCollection().findMany({ filter: { orgId } });
}

export async function getByEmailDomain(domain: string): Promise<EnterpriseIdpDoc | null> {
  // findOne doesn't support ARRAY_CONTAINS; fetch all enabled and filter in-memory
  const all = await idpCollection().findMany({ filter: { enabled: true } });
  return all.find(d => d.emailDomains.includes(domain.toLowerCase())) ?? null;
}

export async function updateIdp(
  id: string,
  orgId: string,
  updates: Partial<EnterpriseIdpDoc>
): Promise<EnterpriseIdpDoc | null> {
  const existing = await getById(id, orgId);
  if (!existing) return null;
  return idpCollection().update(id, orgId, {
    ...updates,
    updatedAt: new Date().toISOString(),
  } as Partial<EnterpriseIdpDoc>);
}

export async function remove(id: string, orgId: string): Promise<boolean> {
  try {
    await idpCollection().delete(id, orgId);
    return true;
  } catch {
    return false;
  }
}
