import 'package:http/http.dart' as http;
import 'package:pocketbase/pocketbase.dart';
import '../../core/api/pocketbase_client.dart';
import '../../models/job_file.dart';

class JobFilesRepository {
  JobFilesRepository._();
  static final instance = JobFilesRepository._();

  PocketBase get _pb => PocketBaseClient.instance.pb;
  static const _baseUrl = 'https://pocket.kovaksoft.com';

  String get _currentUserId => (_pb.authStore.record?.id) ?? '';

  Future<List<JobFile>> listForJob(String jobId) async {
    final result = await _pb.collection('job_files').getList(
      filter: 'job_id = "$jobId"',
      perPage: 200,
    );
    final files = result.items.map((r) => JobFile.fromJson(r.toJson(), _baseUrl)).toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt));
    return files;
  }

  Future<JobFile> uploadFile({
    required String jobId,
    required String clinicTenantId,
    required String labTenantId,
    required JobFileKind kind,
    required String name,
    required int size,
    required List<int> bytes,
    String? mimeType,
  }) async {
    final multipartFile = http.MultipartFile.fromBytes(
      'file',
      bytes,
      filename: name,
    );
    final record = await _pb.collection('job_files').create(
      body: {
        'job_id': jobId,
        'clinic_tenant_id': clinicTenantId,
        'lab_tenant_id': labTenantId,
        'uploaded_by': _currentUserId,
        'kind': kind.value,
        'name': name,
        'size': size,
        if (mimeType != null) 'mime_type': mimeType,
      },
      files: [multipartFile],
    );
    return JobFile.fromJson(record.toJson(), _baseUrl);
  }

  Future<void> deleteFile(String fileId) async {
    await _pb.collection('job_files').delete(fileId);
  }
}
