import type { Querier } from '@platform-modules/db'
import { and, eq } from 'drizzle-orm'
import { supportStateTransitions } from './schema.js'
import type { HelpdeskSchema } from './schema.js'
import type { AppendTransitionInput, ParentKey, SupportStateTransition } from './types.js'

export async function appendTransition<S extends HelpdeskSchema>(
  tx: Querier<S>,
  key: ParentKey,
  input: AppendTransitionInput,
): Promise<SupportStateTransition> {
  const [row] = await tx
    .insert(supportStateTransitions)
    .values({
      parentType: key.parentType,
      parentId: key.parentId,
      fromStatus: input.fromStatus,
      toStatus: input.toStatus,
      actorId: input.actorId,
      reason: input.reason ?? null,
      at: input.at ?? new Date(),
    })
    .returning()

  if (!row) {
    throw new Error('appendTransition: insert returned no row')
  }

  return row
}

export async function listTransitions<S extends HelpdeskSchema>(
  tx: Querier<S>,
  key: ParentKey,
): Promise<SupportStateTransition[]> {
  return tx
    .select()
    .from(supportStateTransitions)
    .where(
      and(
        eq(supportStateTransitions.parentType, key.parentType),
        eq(supportStateTransitions.parentId, key.parentId),
      ),
    )
}
