//
//  PermissionManager.swift
//  AcaMate
//
//  Created by TAnine on 3/28/25.
//

import Foundation
import AVFoundation
import Photos
import CoreLocation
import UserNotifications

class PermissionManager: NSObject, ObservableObject {
        
    private let locationManager = CLLocationManager()
    private var locationRequestCallback: ((CLAuthorizationStatus) -> Void)?
    
    override init() {
        super.init()
        locationManager.delegate = self
    }
    
    // MARK: - 푸시 권한 요청
    func requestPushPermission(completion: @escaping (Bool) -> Void) {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            DispatchQueue.main.async {
                completion(granted)
            }
        }
    }
    
    // MARK: - 카메라 권한 요청
    func requestCameraPermission(completion: @escaping (Bool) -> Void) {
        AVCaptureDevice.requestAccess(for: .video) { granted in
            DispatchQueue.main.async {
                completion(granted)
            }
        }
    }
    
    // MARK: - 앨범 권한 요청
    func requestPhotoPermission(completion: @escaping (PHAuthorizationStatus) -> Void) {
        PHPhotoLibrary.requestAuthorization { status in
            DispatchQueue.main.async {
                completion(status)
            }
        }
    }
    
    // MARK: - 위치 권한 요청
    func requestLocationPermission(completion: @escaping (CLAuthorizationStatus) -> Void) {
        locationRequestCallback = completion
        locationManager.requestWhenInUseAuthorization()
    }
    
    // MARK: - 현재 권한 상태 확인
    func checkPushPermission(completion: @escaping (Bool) -> Void) {
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            DispatchQueue.main.async {
                completion(settings.authorizationStatus == .authorized)
            }
        }
    }
    
    func checkCameraPermission() -> Bool {
        return AVCaptureDevice.authorizationStatus(for: .video) == .authorized
    }
    
    func checkPhotoPermission() -> Bool {
        let status = PHPhotoLibrary.authorizationStatus(for: .readWrite)
        return status == .authorized || status == .limited
    }
    
    func checkLocationPermission() -> Bool {
        let status = locationManager.authorizationStatus
        return status == .authorizedAlways || status == .authorizedWhenInUse
    }
}
extension PermissionManager: CLLocationManagerDelegate {
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        let status = manager.authorizationStatus
        locationRequestCallback?(status)
        locationRequestCallback = nil
    }
}
