import { afterEach, describe, expect, it } from 'vitest';
import { DeliveryService } from '../../src/services/delivery-service.js';
import { InvoiceService } from '../../src/services/invoice-service.js';
import { ReportService } from '../../src/services/report-service.js';
import { createTestContext } from '../helpers.js';

const contexts: Awaited<ReturnType<typeof createTestContext>>[] = [];
afterEach(async () => { while (contexts.length) await contexts.pop()!.db.close(); });

describe('گزارش Excel', () => {
  it('چهار sheet فارسی، RTL، freeze و رنگ سبز وضعیت کامل را ایجاد می‌کند', async () => {
    const context = await createTestContext(); contexts.push(context);
    const invoiceId = await new InvoiceService(context.db).createManual(context.users.supply!.id, {
      invoiceNumber: 'R-100', requesterId: context.requesterId,
      items: [{ productCode: 'RP-1', productName: 'کالای گزارش', unit: 'عدد', quantity: 2 }]
    }, {});
    const delivery = new DeliveryService(context.db);
    const request = await delivery.approve({ id: context.users.supply!.id }, {
      invoiceId, requesterId: context.requesterId, warehouseId: context.warehouseId, deliveryType: 'complete',
      items: [{ productCode: 'RP-1', productName: 'کالای گزارش', unit: 'عدد', quantity: 2 }], idempotencyKey: 'report-approve'
    }, {});
    await delivery.warehouseAction({ id: context.users.warehouse!.id, warehouseId: context.warehouseId }, request.id, 'deliver', 'report-deliver', undefined, {});
    const workbook = await new ReportService(context.db).build({ startUtc: new Date(Date.now() - 60_000), endUtc: new Date(Date.now() + 60_000), label: 'آزمون' });
    expect(workbook.worksheets.map((sheet) => sheet.name)).toEqual(['وضعیت تحویل', 'ثبت خروج تأمین', 'تاریخچه انبارداری', 'تغییرات مالی']);
    const status = workbook.getWorksheet('وضعیت تحویل')!;
    expect(status.views[0]?.rightToLeft).toBe(true);
    expect(status.views[0]?.state).toBe('frozen');
    expect(status.getCell('I2').value).toBe('تحویل کامل');
    expect((status.getRow(2).fill as any).fgColor.argb).toBe('FFD1FAE5');
  });
});
