// iOS helper: Universal Links for an installed app; explicit code entry after App Store install.
// Never read the clipboard silently or embed a SAIRO campaign secret in the app.
import Foundation

public final class SairoReferral {
    private let defaults: UserDefaults
    private let key = "sairo_pending_referral"
    public init(defaults: UserDefaults = .standard) { self.defaults = defaults }
    public var pending: String? { defaults.string(forKey: key) }
    @discardableResult public func capture(_ url: URL) -> Bool {
        let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
        let ref = items.first(where: { $0.name == "ref" || $0.name == "sairo_ref" })?.value
        let code = items.first(where: { $0.name == "sairo_code" })?.value
        if let ref = ref, ref.count <= 2000,
           ref.range(of: "^[A-Za-z0-9_-]+\\.[a-f0-9]{64}$", options: .regularExpression) != nil {
            if pending == nil { defaults.set(ref, forKey: key) }; return true
        }
        return code.map { enterCode($0) } ?? false
    }
    @discardableResult public func enterCode(_ input: String) -> Bool {
        let code = input.replacingOccurrences(of: "-", with: "").trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
        guard code.range(of: "^[A-F0-9]{20}$", options: .regularExpression) != nil else { return false }
        if pending == nil { defaults.set(code, forKey: key) }; return true
    }
    // Call only after your backend commits attribution. Keep pending on network failure.
    public func acknowledge() { defaults.removeObject(forKey: key) }
}
