import 'dart:io';

import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';

class ImageStorageService {
  ImageStorageService({Uuid? uuid}) : _uuid = uuid ?? const Uuid();

  final Uuid _uuid;

  Future<String> storeImage({
    required String sourcePath,
    required String workOrderId,
    required String taskId,
  }) async {
    final documents = await getApplicationDocumentsDirectory();
    final destinationDirectory = Directory(
      p.join(documents.path, 'ot_movil', 'images', workOrderId, taskId),
    );
    await destinationDirectory.create(recursive: true);

    final sourceExtension = p.extension(sourcePath).toLowerCase();
    final extension = sourceExtension.isEmpty ? '.jpg' : sourceExtension;
    final destinationPath = p.join(
      destinationDirectory.path,
      '${_uuid.v4()}$extension',
    );
    await File(sourcePath).copy(destinationPath);
    return destinationPath;
  }

  Future<void> deleteFiles(Iterable<String> paths) async {
    for (final path in paths) {
      final file = File(path);
      if (await file.exists()) {
        await file.delete();
      }
    }
  }

  Future<void> deleteWorkOrderImages(String workOrderId) async {
    final documents = await getApplicationDocumentsDirectory();
    final directory = Directory(
      p.join(documents.path, 'ot_movil', 'images', workOrderId),
    );
    if (await directory.exists()) {
      await directory.delete(recursive: true);
    }
  }
}
