import Photos
import UIKit

enum PhotoSaverError: LocalizedError {
    case denied
    case encodingFailed
    case unknown

    var errorDescription: String? {
        switch self {
        case .denied:
            return "Photo library access was denied."
        case .encodingFailed:
            return "The image could not be encoded."
        case .unknown:
            return "The photo could not be saved."
        }
    }
}

enum PhotoSaver {
    static func save(_ image: UIImage, completion: @escaping (Result<Void, Error>) -> Void) {
        guard image.cgImage != nil else {
            DispatchQueue.main.async { completion(.failure(PhotoSaverError.encodingFailed)) }
            return
        }

        PHPhotoLibrary.requestAuthorization(for: .addOnly) { authorization in
            guard authorization == .authorized || authorization == .limited else {
                DispatchQueue.main.async { completion(.failure(PhotoSaverError.denied)) }
                return
            }

            PHPhotoLibrary.shared().performChanges {
                PHAssetChangeRequest.creationRequestForAsset(from: image)
            } completionHandler: { success, error in
                DispatchQueue.main.async {
                    if success {
                        completion(.success(()))
                    } else {
                        completion(.failure(error ?? PhotoSaverError.unknown))
                    }
                }
            }
        }
    }
}
