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

export type SupportAttachmentRow = InferSelectModel<typeof supportAttachments>;
export type NewSupportAttachment = InferInsertModel<typeof supportAttachments>;

export async function insert(
  db: DrizzleClient,
  values: NewSupportAttachment,
): Promise<SupportAttachmentRow> {
  const [row] = await db.insert(supportAttachments).values(values).returning();
  if (!row) throw new Error('support attachment insert returned no rows');
  return row;
}

export async function listByParent(
  db: DrizzleClient,
  parentType: SupportAttachmentRow['parentType'],
  parentId: string,
) {
  return db
    .select()
    .from(supportAttachments)
    .where(
      and(eq(supportAttachments.parentType, parentType), eq(supportAttachments.parentId, parentId)),
    );
}

export async function findById(
  db: DrizzleClient,
  id: string,
): Promise<SupportAttachmentRow | null> {
  const rows = await db
    .select()
    .from(supportAttachments)
    .where(eq(supportAttachments.id, id))
    .limit(1);
  return rows[0] ?? null;
}

/**
 * Link pre-uploaded attachment IDs to a parent (ticket or case).
 * Uploads are created with parentType='ticket', parentId=null before submission.
 * This call sets the parentId once the parent entity is created.
 */
export async function linkAttachmentsToParent(
  db: DrizzleClient,
  attachmentIds: string[],
  parentType: SupportAttachmentRow['parentType'],
  parentId: string,
): Promise<void> {
  if (attachmentIds.length === 0) return;
  await db
    .update(supportAttachments)
    .set({ parentType, parentId })
    .where(inArray(supportAttachments.id, attachmentIds));
}

export async function updateAbuseStatus(
  db: DrizzleClient,
  id: string,
  abuseStatus: SupportAttachmentRow['abuseStatus'],
): Promise<void> {
  await db.update(supportAttachments).set({ abuseStatus }).where(eq(supportAttachments.id, id));
}

export async function deleteById(db: DrizzleClient, id: string): Promise<void> {
  await db.delete(supportAttachments).where(eq(supportAttachments.id, id));
}
