import 'package:krow_core/core.dart';
import 'package:krow_data_connect/krow_data_connect.dart';
import 'package:krow_domain/krow_domain.dart' as domain;

import '../../domain/repositories/documents_repository.dart';

/// Implementation of [DocumentsRepository] using Data Connect.
class DocumentsRepositoryImpl
    implements DocumentsRepository {
  final DataConnectService _service;

  DocumentsRepositoryImpl() : _service = DataConnectService.instance;

  @override
  Future<List<domain.StaffDocument>> getDocuments() async {
    return _service.run(() async {
      final String? staffId = await _service.getStaffId();

    /// MOCK IMPLEMENTATION
    /// To be replaced with real data connect query when available
    return [
      domain.StaffDocument(
        id: 'doc1',
        staffId: staffId!,
        documentId: 'd1',
        name: 'Work Permit',
        description: 'Valid work permit document',
        status: domain.DocumentStatus.verified,
        documentUrl: 'https://example.com/documents/work_permit.pdf',
        expiryDate: DateTime.now().add(const Duration(days: 365)),
      ),
      domain.StaffDocument(
        id: 'doc2',
        staffId: staffId!,
        documentId: 'd2',
        name: 'Health and Safety Training',
        description: 'Certificate of completion for health and safety training',
        status: domain.DocumentStatus.pending,
        documentUrl: 'https://example.com/documents/health_safety.pdf',
        expiryDate: DateTime.now().add(const Duration(days: 180)),
      ),
    ];

    });
  }

  domain.StaffDocument _mapToDomain(
    ListStaffDocumentsByStaffIdStaffDocuments doc,
  ) {
    return domain.StaffDocument(
      id: doc.id,
      staffId: doc.staffId,
      documentId: doc.documentId,
      name: doc.document.name,
      description: null, // Description not available in data source
      status: _mapStatus(doc.status),
      documentUrl: doc.documentUrl,
      expiryDate: doc.expiryDate == null
          ? null
          : DateTimeUtils.toDeviceTime(doc.expiryDate!.toDateTime()),
    );
  }

  domain.DocumentStatus _mapStatus(EnumValue<DocumentStatus> status) {
    if (status is Known<DocumentStatus>) {
      switch (status.value) {
        case DocumentStatus.VERIFIED:
          return domain.DocumentStatus.verified;
        case DocumentStatus.PENDING:
          return domain.DocumentStatus.pending;
        case DocumentStatus.MISSING:
          return domain.DocumentStatus.missing;
        case DocumentStatus.UPLOADED:
        case DocumentStatus.EXPIRING:
          return domain.DocumentStatus.pending;
      }
    }
    // Default to pending for Unknown or unhandled cases
    return domain.DocumentStatus.pending;
  }
}
