import { Test } from '@nestjs/testing';
import { OriginGoodsService } from './origin-goods.service';
import { PrismaService } from '../prisma/prisma.service';

describe('OriginGoodsService', () => {
  let service: OriginGoodsService;
  let prisma: PrismaService;
  const stamp = Date.now();
  const createdSds: string[] = [];

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({
      providers: [OriginGoodsService, PrismaService],
    }).compile();
    service = moduleRef.get(OriginGoodsService);
    prisma = moduleRef.get(PrismaService);
    await prisma.onModuleInit();

    // Seed 25 rows with sequential goodNames so we can paginate/filter.
    const rows = Array.from({ length: 25 }).map((_, i) => ({
      sdsGoodId: `sds-${stamp}-${i}`,
      goodName: `Origin Good ${stamp} ${i.toString().padStart(2, '0')}`,
      sdsCategoryId: `cat-${stamp}-${i % 3}`,
    }));
    await prisma.originGood.createMany({ data: rows });
    createdSds.push(...rows.map((r) => r.sdsGoodId));
  });

  afterAll(async () => {
    if (createdSds.length) {
      await prisma.originGood.deleteMany({
        where: { sdsGoodId: { in: createdSds } },
      });
    }
    await prisma.onModuleDestroy();
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  it('returns paginated results', async () => {
    const page1 = await service.findAll({
      page: 1,
      pageSize: 10,
      keyword: `Origin Good ${stamp}`,
    });
    expect(page1.total).toBe(25);
    expect(page1.items.length).toBe(10);
    expect(page1.page).toBe(1);
    expect(page1.pageSize).toBe(10);

    const page3 = await service.findAll({
      page: 3,
      pageSize: 10,
      keyword: `Origin Good ${stamp}`,
    });
    expect(page3.items.length).toBe(5);
  });

  it('searches by keyword (case insensitive)', async () => {
    const result = await service.findAll({
      page: 1,
      pageSize: 5,
      keyword: `origin good ${stamp} 05`,
    });
    expect(result.items.length).toBe(1);
    expect(result.items[0].goodName).toContain('05');
  });

  it('returns empty page when no matches', async () => {
    const result = await service.findAll({
      page: 1,
      pageSize: 5,
      keyword: 'definitely-does-not-exist',
    });
    expect(result.total).toBe(0);
    expect(result.items.length).toBe(0);
  });
});
