import 'dart:io';

import 'package:flutter_test/flutter_test.dart';
import 'package:ot_movil/models/work_order.dart';
import 'package:ot_movil/services/pdf_service.dart';

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  test('distingue los informes con la identidad vigente', () {
    final service = PdfService();

    expect(
      service.isCurrentReport('/reports/OT_20260725_abcd1234.pdf'),
      isFalse,
    );
    expect(
      service.isCurrentReport('/reports/OT_v2_20260725_abcd1234.pdf'),
      isFalse,
    );
    expect(
      service.isCurrentReport('/reports/OT_v3_20260725_abcd1234.pdf'),
      isFalse,
    );
    expect(
      service.isCurrentReport('/reports/OT_v4_20260725_abcd1234.pdf'),
      isFalse,
    );
    expect(
      service.isCurrentReport('/reports/OT_v5_20260725_abcd1234.pdf'),
      isFalse,
    );
    expect(
      service.isCurrentReport('/reports/OT_v6_20260725_abcd1234.pdf'),
      isFalse,
    );
    expect(
      service.isCurrentReport('/reports/OT_v7_20260725_abcd1234.pdf'),
      isFalse,
    );
    expect(
      service.isCurrentReport('/reports/OT_v8_20260725_abcd1234.pdf'),
      isFalse,
    );
    expect(
      service.isCurrentReport(
        '/reports/OT_v9_cliente_20260725_abcd1234.pdf',
        type: PdfReportType.client,
      ),
      isFalse,
    );
    expect(
      service.isCurrentReport(
        '/reports/OT_v9_certificadora_20260725_abcd1234.pdf',
        type: PdfReportType.certifier,
      ),
      isFalse,
    );
    expect(
      service.isCurrentReport(
        '/reports/OT_v10_cliente_20260725_abcd1234.pdf',
        type: PdfReportType.client,
      ),
      isFalse,
    );
    expect(
      service.isCurrentReport(
        '/reports/OT_v10_certificadora_20260725_abcd1234.pdf',
        type: PdfReportType.certifier,
      ),
      isFalse,
    );
    expect(
      service.isCurrentReport(
        '/reports/OT_v11_cliente_20260725_abcd1234.pdf',
        type: PdfReportType.client,
      ),
      isFalse,
    );
    expect(
      service.isCurrentReport(
        '/reports/OT_v11_certificadora_20260725_abcd1234.pdf',
        type: PdfReportType.certifier,
      ),
      isFalse,
    );
    expect(
      service.isCurrentReport(
        '/reports/OT_v12_cliente_20260725_abcd1234.pdf',
        type: PdfReportType.client,
      ),
      isTrue,
    );
    expect(
      service.isCurrentReport(
        '/reports/OT_v12_certificadora_20260725_abcd1234.pdf',
        type: PdfReportType.certifier,
      ),
      isTrue,
    );
    expect(
      service.isCurrentReport(
        '/reports/OT_v12_cliente_20260725_abcd1234.pdf',
        type: PdfReportType.certifier,
      ),
      isFalse,
    );
  });

  test('genera los informes para cliente y empresa certificadora', () async {
    final completedAt = DateTime(2026, 7, 25, 16, 30);
    final order = WorkOrder(
      id: '12345678-1234-1234-1234-123456789012',
      title: 'Mantención Preventiva',
      createdAt: completedAt.subtract(const Duration(hours: 2)),
      updatedAt: completedAt,
      completedAt: completedAt,
      status: WorkOrderStatus.completed,
      laborCost: 40000,
      details: const WorkOrderDetails(
        client: 'Cliente de prueba',
        phone: '+56 9 9999 0000',
        address: 'Av. Principal 123, Santiago',
      ),
      tasks: List.generate(
        8,
        (index) => WorkTask(
          id: 'task-$index',
          title: index.isEven ? 'Limpieza Full' : 'Chequeo de gas refrigerante',
          observation:
              'Se realizó la inspección del equipo, la limpieza de sus '
              'componentes y la verificación de los parámetros de operación. '
              'El equipo quedó funcionando correctamente.',
          position: index,
          parts: index == 0
              ? const [
                  TaskPart(
                    id: 'part-1',
                    name: 'Flexible de agua 1/2 pulgada',
                    price: 8500,
                  ),
                  TaskPart(id: 'part-2', name: 'Llave de paso', price: 12990),
                ]
              : const [],
          photos: index == 0
              ? List.generate(
                  3,
                  (photoIndex) => TaskPhoto(
                    id: 'before-$photoIndex',
                    path: 'assets/pdf/simon_moya_report_logo.png',
                    kind: PhotoKind.before,
                  ),
                )
              : const [],
        ),
      ),
    );

    final service = PdfService();
    final clientBytes = await service.build(order, type: PdfReportType.client);
    final certifierBytes = await service.build(
      order,
      type: PdfReportType.certifier,
    );

    expect(clientBytes, isNotEmpty);
    expect(certifierBytes, isNotEmpty);
    expect(String.fromCharCodes(clientBytes.take(4)), '%PDF');
    expect(String.fromCharCodes(certifierBytes.take(4)), '%PDF');
    expect(clientBytes, isNot(equals(certifierBytes)));

    const samplePath = String.fromEnvironment('PDF_SAMPLE_PATH');
    if (samplePath.isNotEmpty) {
      final file = File(samplePath);
      await file.parent.create(recursive: true);
      await file.writeAsBytes(clientBytes, flush: true);
    }

    const certifierSamplePath = String.fromEnvironment(
      'PDF_CERTIFIER_SAMPLE_PATH',
    );
    if (certifierSamplePath.isNotEmpty) {
      final file = File(certifierSamplePath);
      await file.parent.create(recursive: true);
      await file.writeAsBytes(certifierBytes, flush: true);
    }
  });
}
