//
//  EncodableSDKState.swift
//  RNRookSdk
//
//  Created by Javier Villanueva on 07/04/26.
//

import Foundation
import RookSDK

private struct DateTransformer {
    static let localFormatter: DateFormatter = {
        let formatter = DateFormatter()
        // Use a standard ISO-like format or customize as needed
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
        formatter.timeZone = .current // Explicitly set to the device's local timezone
        return formatter
    }()
    
    static func string(from date: Date?) -> String? {
        guard let date = date else { return nil }
        return localFormatter.string(from: date)
    }
}

public struct EncodableSDKState: Encodable {
    
  private let state: RookSDK.SDKState

  public init(_ state: RookSDK.SDKState) {
        self.state = state
    }

    private enum CodingKeys: String, CodingKey {
        case isConfigured
        case userIdentified
        case permissions
        case backgroundSync
        case manualSync
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encode(state.isConfigured, forKey: .isConfigured)
        try container.encode(state.userIdentified, forKey: .userIdentified)
        try container.encode(state.permissions, forKey: .permissions)
        
        // Wrap nested structs to ensure they use their own encoding logic
        try container.encode(EncodableSDKBackgroundState(state.backgroundSync), forKey: .backgroundSync)
        try container.encode(EncodableSDKManualSyncState(state.manualSync), forKey: .manualSync)
    }
}

// MARK: - Nested Wrappers

struct EncodableSDKBackgroundState: Encodable {
  private let backgroundState: RookSDK.SDKBackgroundState
  private let formatter = ISO8601DateFormatter()
    
  init(_ backgroundState: RookSDK.SDKBackgroundState) {
        self.backgroundState = backgroundState
    }
    
    private enum CodingKeys: String, CodingKey {
        case enabled, lastSync
    }
    
  func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(backgroundState.enabled, forKey: .enabled)
    
    try container.encode(DateTransformer.string(from: backgroundState.lastSync), forKey: .lastSync)
  }
}

struct EncodableSDKManualSyncState: Encodable {
  private let manualState: RookSDK.SDKManualSyncState
  private let formatter = ISO8601DateFormatter()
    
  init(_ manualState: RookSDK.SDKManualSyncState) {
        self.manualState = manualState
    }
    
    private enum CodingKeys: String, CodingKey {
        case enabled, lastSync
    }
    
  func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(manualState.enabled, forKey: .enabled)
    
    try container.encode(DateTransformer.string(from: manualState.lastSync), forKey: .lastSync)
  }
}
