import { eq, and, isNull, desc } from 'drizzle-orm';
import type { DrizzleClient } from '../client';
import { supportMessages } from '../schema';
import type { InferInsertModel, InferSelectModel } from 'drizzle-orm';
import { encryptMessageBody } from '@/server/support/messages';

export type SupportMessageRow = InferSelectModel<typeof supportMessages>;
export type NewSupportMessage = InferInsertModel<typeof supportMessages>;

export async function insertEncrypted(
  db: DrizzleClient,
  row: Omit<NewSupportMessage, 'bodyEncrypted'>,
  plaintext: string,
  key: string,
): Promise<SupportMessageRow> {
  const [result] = await db
    .insert(supportMessages)
    .values({ ...row, bodyEncrypted: encryptMessageBody(plaintext, key) as unknown as string })
    .returning();
  return result!;
}

export async function listByParent(
  db: DrizzleClient,
  parentType: SupportMessageRow['parentType'],
  parentId: string,
  viewerRole: 'customer' | 'vendor' | 'admin',
) {
  const visibilityConds = [];
  if (viewerRole === 'customer') {
    visibilityConds.push(eq(supportMessages.visibility, 'public'));
  } else if (viewerRole === 'vendor') {
    // vendor can see public + vendor_internal
    // drizzle doesn't have inArray for enums simply, use two OR conditions
  }
  // admin sees all — no filter needed

  const baseConds = [
    eq(supportMessages.parentType, parentType),
    eq(supportMessages.parentId, parentId),
    isNull(supportMessages.deletedAt),
  ];

  if (viewerRole === 'customer') {
    baseConds.push(eq(supportMessages.visibility, 'public'));
  }

  return db
    .select()
    .from(supportMessages)
    .where(and(...baseConds))
    .orderBy(desc(supportMessages.createdAt));
}

export async function softDelete(db: DrizzleClient, id: string): Promise<void> {
  await db.update(supportMessages).set({ deletedAt: new Date() }).where(eq(supportMessages.id, id));
}
