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

export async function addAttachment<S extends HelpdeskSchema>(
  tx: Querier<S>,
  key: ParentKey,
  input: AddAttachmentInput,
): Promise<SupportAttachment> {
  const [row] = await tx
    .insert(supportAttachments)
    .values({
      parentType: key.parentType,
      parentId: key.parentId,
      objectKey: input.objectKey,
      fileName: input.fileName ?? null,
      mimeType: input.mimeType ?? null,
    })
    .returning()

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

  return row
}

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