//
//  See LICENSE folder for this template’s licensing information.
//
//  Abstract:
//  Web Authentication （認証用）


import Foundation
import AudioToolbox

import Foundation

public protocol HTTPAuthDelegate: AnyObject {
    func didWebAuthenticateSuccess()
    func didWebAuthenticateFailWithError(_ error: Error)
}

public class HTTPAuth {
    private let url: URL
    private let schoolId: String
    public weak var delegate: HTTPAuthDelegate?
    
    public init(url: URL, schoolId: String) {
        self.url = url
        self.schoolId = schoolId
    }
    
    public func authenticate() {
        // URLにクエリパラメータを追加
        let urlString = "\(url.absoluteString)?schoolId=\(schoolId)"
        guard let url = URL(string: urlString) else { return }
        
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        
        if schoolId.isEmpty {
            //let error = NSError(domain: "HTTPAuthError", code: 0, userInfo: [NSLocalizedDescriptionKey: "\nスクールIDが設定されていません。\(schoolId)"])
            //self.handleError(error)
            return
        }
        
        let task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
            if let error = error {
                self?.handleError(error)
                return
            }
            
            guard let data = data else {
                //let error = NSError(domain: "HTTPAuthError", code: 0, userInfo: [NSLocalizedDescriptionKey: "No data received"])
                //self?.handleError(error)
                return
            }

            self?.parseAuthenticationResponse(data: data)
        }
        task.resume()
    }
    
    private func handleError(_ error: Error) {
        self.delegate?.didWebAuthenticateFailWithError(error)
    }
    
    private func parseAuthenticationResponse(data: Data) {
        do {
            if let jsonResponse = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
               let status = jsonResponse["status"] as? String {
                if status == "Success" {
                    self.delegate?.didWebAuthenticateSuccess()
                } else {
                    //let errorMessage = jsonResponse["message"] as? String ?? "Unknown error"
                    //let error = NSError(domain: "HTTPAuthError", code: 0, userInfo: [NSLocalizedDescriptionKey: errorMessage])
                    //self.handleError(error)
                }
            } else {
                let error = NSError(domain: "HTTPAuthError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid JSON format"])
                self.handleError(error)
            }
        } catch {
            self.handleError(error)
        }
    }
}
