//
//  PhotoLibraryService.swift
//  CameraTester
//
//  Created by Matt Bruce on 1/3/26.
//

import Photos
import SwiftUI

/// Errors that can occur during photo library operations
enum PhotoLibraryError: Error {
    case accessDenied
    case conversionFailed
    case saveFailed(String)

    var localizedDescription: String {
        switch self {
        case .accessDenied:
            return "Photos access denied. Please enable in Settings."
        case .conversionFailed:
            return "Failed to convert image to JPEG format"
        case .saveFailed(let message):
            return "Failed to save photo: \(message)"
        }
    }
}

/// Service for handling photo library operations
@MainActor
class PhotoLibraryService {
    /// Save a photo to the user's photo library
    /// - Parameters:
    ///   - image: The UIImage to save
    ///   - quality: The photo quality setting for JPEG compression
    /// - Returns: Result indicating success or error
    static func savePhotoToLibrary(_ image: UIImage, quality: PhotoQuality) async -> Result<Void, PhotoLibraryError> {
        let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly)

        guard status == .authorized || status == .limited else {
            return .failure(.accessDenied)
        }

        // Convert image to JPEG data using selected quality
        guard let imageData = image.jpegData(compressionQuality: quality.compressionQuality) else {
            return .failure(.conversionFailed)
        }

        do {
            try await PHPhotoLibrary.shared().performChanges {
                let options = PHAssetResourceCreationOptions()
                PHAssetCreationRequest.forAsset().addResource(with: .photo, data: imageData, options: options)
            }
            return .success(())
        } catch {
            return .failure(.saveFailed(error.localizedDescription))
        }
    }
}
