import { and, eq, isNull } from 'drizzle-orm';
import type { DrizzleClient } from '../client';
import { caseResolutions } from '../schema';
import type { InferInsertModel, InferSelectModel } from 'drizzle-orm';
import { asCaseId } from '../../platform-seams/ids';

export type CaseResolutionRow = InferSelectModel<typeof caseResolutions>;
export type NewCaseResolution = InferInsertModel<typeof caseResolutions>;

/** Insert a resolution. caseId has a unique constraint — will throw if duplicate. */
export async function insert(
  db: DrizzleClient,
  values: NewCaseResolution,
): Promise<CaseResolutionRow> {
  const [row] = await db.insert(caseResolutions).values(values).returning();
  return row!;
}

export async function insertIfAbsent(
  db: DrizzleClient,
  values: NewCaseResolution,
): Promise<CaseResolutionRow | null> {
  const [row] = await db
    .insert(caseResolutions)
    .values(values)
    .onConflictDoNothing({ target: caseResolutions.caseId })
    .returning();
  return row ?? null;
}

export async function findByCase(
  db: DrizzleClient,
  caseId: string,
): Promise<CaseResolutionRow | null> {
  const rows = await db
    .select()
    .from(caseResolutions)
    .where(eq(caseResolutions.caseId, asCaseId(caseId)))
    .limit(1);
  return rows[0] ?? null;
}

export async function completeProviderRefund(
  db: DrizzleClient,
  input: { caseId: string; providerRefundId: string },
): Promise<CaseResolutionRow | null> {
  const [row] = await db
    .update(caseResolutions)
    .set({ providerRefundId: input.providerRefundId })
    .where(
      and(
        eq(caseResolutions.caseId, asCaseId(input.caseId)),
        isNull(caseResolutions.providerRefundId),
      ),
    )
    .returning();
  return row ?? null;
}
