import { eq, and, desc } from 'drizzle-orm';
import type { DrizzleClient } from '../client';
import { supportStateTransitions } from '../schema';
import type { InferInsertModel, InferSelectModel } from 'drizzle-orm';

export type SupportStateTransitionRow = InferSelectModel<typeof supportStateTransitions>;
export type NewSupportStateTransition = InferInsertModel<typeof supportStateTransitions>;
type TransitionWriter = Pick<DrizzleClient, 'insert'>;
type TransitionReader = Pick<DrizzleClient, 'select'>;

export async function insert(
  db: TransitionWriter,
  values: NewSupportStateTransition,
): Promise<SupportStateTransitionRow> {
  const [row] = await db.insert(supportStateTransitions).values(values).returning();
  return row!;
}

export async function listByParent(
  db: TransitionReader,
  parentType: SupportStateTransitionRow['parentType'],
  parentId: string,
) {
  return db
    .select()
    .from(supportStateTransitions)
    .where(
      and(
        eq(supportStateTransitions.parentType, parentType),
        eq(supportStateTransitions.parentId, parentId),
      ),
    )
    .orderBy(desc(supportStateTransitions.createdAt));
}
