/**
 * User Impersonation repository — Cosmos DB CRUD.
 */

import { getRegisteredContainer } from '@bytelyst/cosmos';
import crypto from 'node:crypto';
import type { ImpersonationSessionDoc, StartImpersonationInput } from './types.js';

function getContainer() {
  return getRegisteredContainer('impersonation_sessions');
}

export async function startImpersonation(
  productId: string,
  adminUserId: string,
  input: StartImpersonationInput
): Promise<ImpersonationSessionDoc> {
  const now = new Date().toISOString();
  const doc: ImpersonationSessionDoc = {
    id: `imp_${crypto.randomUUID()}`,
    productId,
    adminUserId,
    targetUserId: input.targetUserId,
    reason: input.reason,
    active: true,
    startedAt: now,
    endedAt: null,
    createdAt: now,
  };
  await getContainer().items.create(doc);
  return doc;
}

export async function stopImpersonation(
  sessionId: string,
  productId: string
): Promise<ImpersonationSessionDoc | null> {
  try {
    const { resource } = await getContainer()
      .item(sessionId, productId)
      .read<ImpersonationSessionDoc>();
    if (!resource || !resource.active) return null;
    const updated = { ...resource, active: false, endedAt: new Date().toISOString() };
    await getContainer().item(sessionId, productId).replace(updated);
    return updated;
  } catch {
    return null;
  }
}

export async function getActiveSession(
  productId: string,
  adminUserId: string
): Promise<ImpersonationSessionDoc | null> {
  const { resources } = await getContainer()
    .items.query<ImpersonationSessionDoc>({
      query:
        'SELECT * FROM c WHERE c.productId = @pid AND c.adminUserId = @aid AND c.active = true',
      parameters: [
        { name: '@pid', value: productId },
        { name: '@aid', value: adminUserId },
      ],
    })
    .fetchAll();
  return resources[0] ?? null;
}

export async function listSessions(
  productId: string,
  limit: number = 50
): Promise<ImpersonationSessionDoc[]> {
  const { resources } = await getContainer()
    .items.query<ImpersonationSessionDoc>({
      query:
        'SELECT * FROM c WHERE c.productId = @pid ORDER BY c.createdAt DESC OFFSET 0 LIMIT @limit',
      parameters: [
        { name: '@pid', value: productId },
        { name: '@limit', value: limit },
      ],
    })
    .fetchAll();
  return resources;
}
