import { and, eq } from 'drizzle-orm';
import { supportAttachments } from '@/server/db/schema';
import type { KnowledgeAdapter, KnowledgeChunk } from './types';
import type { AdapterContext } from '@/server/support/types';

const LABEL = 'קבצים מצורפים';

export const attachmentsAdapter: KnowledgeAdapter = {
  id: 'attachments',
  label: LABEL,
  description: 'קבצים שהועלו לפנייה',
  async fetch(ctx: AdapterContext): Promise<KnowledgeChunk> {
    const base: KnowledgeChunk = {
      adapterId: 'attachments',
      label: LABEL,
      data: {},
      summary: '',
    };

    try {
      const rows = await ctx.db
        .select({
          id: supportAttachments.id,
          mime: supportAttachments.mime,
          sizeBytes: supportAttachments.sizeBytes,
          cfImageId: supportAttachments.cfImageId,
          abuseStatus: supportAttachments.abuseStatus,
          createdAt: supportAttachments.createdAt,
        })
        .from(supportAttachments)
        .where(
          and(
            eq(supportAttachments.parentType, ctx.parentType),
            eq(supportAttachments.parentId, ctx.parentId),
          ),
        )
        .limit(20);

      const files = rows.map((r) => ({
        id: r.id,
        mime: r.mime,
        sizeBytes: r.sizeBytes,
        cfImageId: r.cfImageId,
        abuseStatus: r.abuseStatus,
        createdAt: r.createdAt.toISOString(),
      }));

      const summary =
        files.length === 0
          ? 'אין קבצים מצורפים'
          : files.map((f) => `${f.cfImageId} (${f.mime})`).join(', ');

      return {
        ...base,
        data: { count: files.length, files },
        summary,
      };
    } catch (err) {
      return { ...base, error: String(err) };
    }
  },
};
