import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
import { PrismaClient } from '@prisma/client';
import { resetDb } from '../test-utils/reset-db';
import { makeFakePorts, portalMessageBasic } from '@insignia/iios-testkit';
import { IngestService } from '../interactions/ingest.service';
import { ThreadsService } from './threads.service';
import type { PrismaService } from '../prisma/prisma.service';

const url = process.env.DATABASE_URL ?? 'postgresql://iios:iios@localhost:5434/iios?schema=public';
const prisma = new PrismaClient({ datasources: { db: { url } } });
const asService = prisma as unknown as PrismaService;

async function clean(): Promise<void> {
  await resetDb(prisma);
}

beforeAll(async () => { await prisma.$connect(); });
afterAll(async () => { await prisma.$disconnect(); });
beforeEach(async () => { await clean(); });

describe('GET thread messages', () => {
  it('returns the stored message part for the thread', async () => {
    const ports = makeFakePorts();
    const ingest = new IngestService(asService, ports);
    const res = await ingest.ingest(portalMessageBasic, 'idem-thread-1');

    const threads = new ThreadsService(asService, ports);
    const out = await threads.getMessages(res.threadId);

    expect(out.messages).toHaveLength(1);
    expect(out.messages[0]?.parts[0]?.bodyText).toBe('my payment failed');
    expect(out.messages[0]?.kind).toBe('MESSAGE');
  });
});
