//
//  PhotoLibrarySaver.swift
//  ylgamehall
//
//  保存 UIImage 到系统相册（with addOnly 权限检查）。
//
//  iOS 14+ 推荐用 PHAccessLevel.addOnly（仅写入相册不读取），权限弹窗
//  比 readWrite 更友好。Info.plist 需配 NSPhotoLibraryAddUsageDescription。
//
//  Phase 4.D / 4.F 分享场景用：抖音 + QQ 图片分享前先保存到相册。
//

import UIKit
import Photos

public enum PhotoLibrarySaverError: Error, Sendable {
    case permissionDenied
    case saveFailed(any Error)
}

@MainActor
public enum PhotoLibrarySaver {

    /// 保存图片到相册。内部处理权限（addOnly 级别）。
    public static func save(_ image: UIImage) async throws {
        let status = PHPhotoLibrary.authorizationStatus(for: .addOnly)
        switch status {
        case .authorized, .limited:
            break
        case .denied, .restricted:
            throw PhotoLibrarySaverError.permissionDenied
        case .notDetermined:
            let newStatus = await PHPhotoLibrary.requestAuthorization(for: .addOnly)
            guard newStatus == .authorized || newStatus == .limited else {
                throw PhotoLibrarySaverError.permissionDenied
            }
        @unknown default:
            throw PhotoLibrarySaverError.permissionDenied
        }

        try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in
            PHPhotoLibrary.shared().performChanges {
                PHAssetChangeRequest.creationRequestForAsset(from: image)
            } completionHandler: { success, error in
                if success {
                    cont.resume()
                } else {
                    cont.resume(throwing: PhotoLibrarySaverError.saveFailed(
                        error ?? NSError(domain: "PhotoLibrarySaver", code: -1)
                    ))
                }
            }
        }
    }
}
