//
//  PhotoLibrarySaver.swift
//  suixinkan
//

import Photos
import UIKit

/// 将图片保存到系统相册，供收款二维码保存使用。
enum PhotoLibrarySaver {

    /// 请求写入权限并将图片保存到相册。
    static func saveImage(_ image: UIImage) async -> Bool {
        let status = await requestAuthorizationIfNeeded()
        guard status == .authorized || status == .limited else {
            return false
        }

        return await withCheckedContinuation { continuation in
            PHPhotoLibrary.shared().performChanges({
                PHAssetChangeRequest.creationRequestForAsset(from: image)
            }, completionHandler: { success, _ in
                continuation.resume(returning: success)
            })
        }
    }

    private static func requestAuthorizationIfNeeded() async -> PHAuthorizationStatus {
        let current = PHPhotoLibrary.authorizationStatus(for: .addOnly)
        switch current {
        case .notDetermined:
            return await PHPhotoLibrary.requestAuthorization(for: .addOnly)
        default:
            return current
        }
    }
}
