//
//  TSAIChatHistoryVM.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/12.
//

class TSAIChatHistoryVM {
    
    lazy var historyDBChatList: [TSDBAIChatList] = {
        let list = TSDBAIChatList.getAll()
        return list
    }()
    
    lazy var historyModelChatList: [TSAIChatHistoryModel] = {
        return categorizeDates()
    }()
    
    func categorizeDates() -> [TSAIChatHistoryModel] {
        let calendar = Calendar.current
        let now = Date()
        let todayStart = calendar.startOfDay(for: now)
        let yesterdayStart = calendar.date(byAdding: .day, value: -1, to: todayStart)!
        let oneWeekAgo = calendar.date(byAdding: .day, value: -7, to: todayStart)!
        let thirtyDaysAgo = calendar.date(byAdding: .day, value: -30, to: todayStart)!
        
        var todayDates: [TSDBAIChatList] = []
        var yesterdayDates: [TSDBAIChatList] = []
        var withinWeekDates: [TSDBAIChatList] = []
        var within30DaysDates: [TSDBAIChatList] = []
        
        for model in historyDBChatList {
            let date = Date(timeIntervalSince1970: TimeInterval(model.creatTimestampInt))
            let dateStart = calendar.startOfDay(for: date)
            if dateStart == todayStart {
                todayDates.append(model)
            } else if dateStart == yesterdayStart {
                yesterdayDates.append(model)
            } else if dateStart > oneWeekAgo {
                withinWeekDates.append(model)
            } else if dateStart > thirtyDaysAgo {
                within30DaysDates.append(model)
            }
        }
        
        todayDates = todayDates.sorted { $0.creatTimestampInt > $1.creatTimestampInt}
        yesterdayDates = yesterdayDates.sorted { $0.creatTimestampInt > $1.creatTimestampInt }
        withinWeekDates = withinWeekDates.sorted { $0.creatTimestampInt > $1.creatTimestampInt }
        within30DaysDates = within30DaysDates.sorted { $0.creatTimestampInt > $1.creatTimestampInt }
        
        var result = [TSAIChatHistoryModel]()
        
        if todayDates.count > 0 {
            result.append(TSAIChatHistoryModel(title: "Today".localized, chatList: todayDates))
        }
        
        if yesterdayDates.count > 0 {
            result.append(TSAIChatHistoryModel(title: "1 Days".localized, chatList: yesterdayDates))
        }
        
        if withinWeekDates.count > 0 {
            result.append(TSAIChatHistoryModel(title: "7 Days".localized, chatList: withinWeekDates))
        }
        
        if within30DaysDates.count > 0 {
            result.append(TSAIChatHistoryModel(title: "30 Days".localized, chatList: within30DaysDates))
        }
        
        return result
    }

    
    func deleteAll() {
        
        TSDBAIChatList.deleteAll()
    }
}
