//
//  LotteryChecker.swift
//  LotteryTracker
//
//  Created by aaa on 2026/1/22.
//

import Foundation
internal import CoreData
import UserNotifications

class LotteryChecker {
    private let context: NSManagedObjectContext
    private let notificationService = NotificationService()
    
    init(context: NSManagedObjectContext) {
        self.context = context
    }
    
    // 检查开奖结果（模拟）
    func checkDrawResults() {
        print("🔍 开始检查开奖结果...")
        
        let request = LotteryTicket.fetchRequest()
        let predicate = NSPredicate(format: "status == %@", TicketStatus.pending.rawValue)
        request.predicate = predicate
        
        guard let pendingTickets = try? context.fetch(request) else {
            print("❌ 获取待开奖记录失败")
            return
        }
        
        let now = Date()
        var updatedCount = 0
        
        for ticket in pendingTickets {
            guard let drawDate = ticket.drawDate else { continue }
            
            // 如果开奖日期已过
            if drawDate <= now {
                // 模拟开奖结果（实际应用中应调用真实API）
                let isWin = Bool.random()
                let winMultiplier = Float.random(in: 1...100)
                
                ticket.ticketStatus = isWin ? .won : .lost
                ticket.prizeAmount = isWin ? ticket.amount * winMultiplier : 0
                
                updatedCount += 1
                
                print("🎯 票券 \(ticket.id?.uuidString.prefix(8) ?? "未知") 开奖结果: \(ticket.ticketStatus.rawValue)")
                
                // 发送通知
                if isWin {
                    notificationService.sendWinNotification(
                        amount: ticket.prizeAmount,
                        ticketType: ticket.lotteryType.rawValue
                    )
                }
            }
        }
        
        if updatedCount > 0 {
            do {
                try context.save()
                print("✅ 更新了 \(updatedCount) 条开奖结果")
                
                // 发送更新通知
                NotificationCenter.default.post(name: .ticketsUpdated, object: nil)
            } catch {
                print("❌ 保存开奖结果失败: \(error)")
            }
        } else {
            print("📭 暂无需要开奖的记录")
        }
    }
    
    // 检查即将开奖的记录
    func checkUpcomingDraws() {
        let request = LotteryTicket.fetchRequest()
        let predicate = NSPredicate(format: "status == %@", TicketStatus.pending.rawValue)
        request.predicate = predicate
        
        guard let pendingTickets = try? context.fetch(request) else { return }
        
        let calendar = Calendar.current
        let now = Date()
        
        for ticket in pendingTickets {
            guard let drawDate = ticket.drawDate else { continue }
            
            // 计算距离开奖的天数
            let components = calendar.dateComponents([.day, .hour], from: now, to: drawDate)
            
            // 如果24小时内开奖，发送提醒
            if let days = components.day, days == 0, let hours = components.hour, hours <= 24 {
                notificationService.sendUpcomingDrawNotification(
                    ticketType: ticket.lotteryType.rawValue,
                    drawDate: drawDate
                )
            }
        }
    }
    
    // 手动开奖（测试用）
    func manualDraw(for ticketId: UUID) -> Bool {
        let request = LotteryTicket.fetchRequest()
        request.predicate = NSPredicate(format: "id == %@", ticketId as CVarArg)
        
        guard let tickets = try? context.fetch(request),
              let ticket = tickets.first,
              ticket.ticketStatus == .pending else {
            return false
        }
        
        // 模拟开奖
        let isWin = Bool.random()
        let winMultiplier = Float.random(in: 1...50)
        
        ticket.ticketStatus = isWin ? .won : .lost
        ticket.prizeAmount = isWin ? ticket.amount * winMultiplier : 0
        
        do {
            try context.save()
            
            // 发送更新通知
            NotificationCenter.default.post(name: .ticketsUpdated, object: nil)
            
            return true
        } catch {
            print("❌ 手动开奖失败: \(error)")
            return false
        }
    }
}

// 通知服务
class NotificationService {
    private let center = UNUserNotificationCenter.current()
    
    init() {
        requestAuthorization()
    }
    
    private func requestAuthorization() {
        center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if granted {
                print("✅ 通知权限已获取")
            } else if let error = error {
                print("❌ 通知权限获取失败: \(error)")
            }
        }
    }
    
    func sendWinNotification(amount: Float, ticketType: String) {
        let content = UNMutableNotificationContent()
        content.title = "🎉 恭喜中奖！"
        content.body = "您的\(ticketType)中奖了！奖金：" + Formatters.formatCurrency(amount)
        content.sound = .default
        
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
        let request = UNNotificationRequest(
            identifier: UUID().uuidString,
            content: content,
            trigger: trigger
        )
        
        center.add(request) { error in
            if let error = error {
                print("❌ 发送中奖通知失败: \(error)")
            }
        }
    }
    
    func sendUpcomingDrawNotification(ticketType: String, drawDate: Date) {
        let formatter = DateFormatter()
        formatter.dateFormat = "MM月dd日 HH:mm"
        
        let content = UNMutableNotificationContent()
        content.title = "⏰ 开奖提醒"
        content.body = "您的\(ticketType)将于\(formatter.string(from: drawDate))开奖"
        content.sound = .default
        
        // 提前1小时提醒
        let triggerDate = Calendar.current.date(byAdding: .hour, value: -1, to: drawDate)!
        let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: triggerDate)
        let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
        
        let request = UNNotificationRequest(
            identifier: "upcoming_draw_\(ticketType)",
            content: content,
            trigger: trigger
        )
        
        center.add(request)
    }
}
