enum JobFileKind { scan, image, document }

extension JobFileKindExt on JobFileKind {
  String get label => switch (this) {
        JobFileKind.scan => 'Tarama',
        JobFileKind.image => 'Görsel',
        JobFileKind.document => 'Belge',
      };
  String get value => switch (this) {
        JobFileKind.scan => 'scan',
        JobFileKind.image => 'image',
        JobFileKind.document => 'document',
      };

  static JobFileKind fromValue(String s) => switch (s) {
        'image' => JobFileKind.image,
        'document' => JobFileKind.document,
        _ => JobFileKind.scan,
      };
}

class JobFile {
  const JobFile({
    required this.id,
    required this.jobId,
    required this.clinicTenantId,
    required this.labTenantId,
    required this.uploadedBy,
    required this.kind,
    required this.fileName,
    required this.name,
    required this.size,
    required this.createdAt,
    required this.downloadUrl,
    this.mimeType,
  });

  final String id;
  final String jobId;
  final String clinicTenantId;
  final String labTenantId;
  final String uploadedBy;
  final JobFileKind kind;
  final String fileName;
  final String name;
  final int size;
  final String? mimeType;
  final DateTime createdAt;
  final String downloadUrl;

  String get sizeLabel {
    if (size < 1024) return '$size B';
    if (size < 1024 * 1024) return '${(size / 1024).toStringAsFixed(1)} KB';
    return '${(size / (1024 * 1024)).toStringAsFixed(2)} MB';
  }

  factory JobFile.fromJson(Map<String, dynamic> j, String baseUrl) {
    String str(String key, [String fallback = '']) =>
        (j[key] as String?) ?? fallback;
    final id = str('id');
    final collectionId = str('collectionId', 'job_files');
    final fileName = str('file');
    final url = fileName.isNotEmpty
        ? '$baseUrl/api/files/$collectionId/$id/$fileName'
        : '';
    final createdRaw = str('created');
    return JobFile(
      id: id,
      jobId: str('job_id'),
      clinicTenantId: str('clinic_tenant_id'),
      labTenantId: str('lab_tenant_id'),
      uploadedBy: str('uploaded_by'),
      kind: JobFileKindExt.fromValue(str('kind')),
      fileName: fileName,
      name: str('name'),
      size: (j['size'] as num?)?.toInt() ?? 0,
      mimeType: j['mime_type'] as String?,
      createdAt: createdRaw.isNotEmpty
          ? DateTime.tryParse(createdRaw) ?? DateTime(2000)
          : DateTime(2000),
      downloadUrl: url,
    );
  }
}
