//
//  ScenicQueueQRCodeSaver.swift
//  suixinkan
//

import Foundation
import Photos
import UIKit

/// 排队二维码保存服务。
enum ScenicQueueQRCodeSaver {
    /// 下载二维码图片并保存到系统相册。
    static func saveImage(from urlString: String) async throws {
        guard let url = URL(string: urlString) else {
            throw ScenicQueueQRCodeSaverError.invalidURL
        }
        let (data, _) = try await URLSession.shared.data(from: url)
        guard let image = UIImage(data: data) else {
            throw ScenicQueueQRCodeSaverError.invalidImage
        }
        try await saveToPhotoLibrary(image)
    }

    private static func saveToPhotoLibrary(_ image: UIImage) async throws {
        let status = PHPhotoLibrary.authorizationStatus(for: .addOnly)
        if status == .notDetermined {
            _ = await PHPhotoLibrary.requestAuthorization(for: .addOnly)
        }
        guard PHPhotoLibrary.authorizationStatus(for: .addOnly) == .authorized
                || PHPhotoLibrary.authorizationStatus(for: .addOnly) == .limited else {
            throw ScenicQueueQRCodeSaverError.denied
        }
        try await PHPhotoLibrary.shared().performChanges {
            PHAssetChangeRequest.creationRequestForAsset(from: image)
        }
    }
}

/// 排队二维码保存错误。
enum ScenicQueueQRCodeSaverError: LocalizedError {
    case invalidURL
    case invalidImage
    case denied

    var errorDescription: String? {
        switch self {
        case .invalidURL:
            "服务端返回的二维码地址无效"
        case .invalidImage:
            "下载或保存二维码失败，请检查网络与存储权限"
        case .denied:
            "未授予权限，无法将小程序码保存到相册"
        }
    }
}
