package com.yourname.premiumah.manager;

import com.yourname.premiumah.model.ClaimRecord;
import com.yourname.premiumah.model.ClaimType;
import com.yourname.premiumah.storage.StorageManager;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

public final class ClaimManager {
    private final StorageManager storageManager;
    private final Map<String, ClaimRecord> claims = new LinkedHashMap<>();

    public ClaimManager(StorageManager storageManager) {
        this.storageManager = storageManager;
    }

    public synchronized void loadFromStorage() {
        claims.clear();
        claims.putAll(storageManager.claimsSnapshot());
    }

    public synchronized void saveToStorage() {
        storageManager.replaceClaims(claims);
    }

    public synchronized void clear() {
        claims.clear();
    }

    public synchronized void add(ClaimRecord claim) {
        claims.put(claim.id(), claim);
    }

    public synchronized Optional<ClaimRecord> get(String id) {
        if (id == null) {
            return Optional.empty();
        }
        return Optional.ofNullable(claims.get(id));
    }

    public synchronized void remove(String id) {
        claims.remove(id);
    }

    public synchronized List<ClaimRecord> claimsFor(UUID ownerUuid) {
        return claims.values().stream()
                .filter(claim -> claim.ownerUuid().equals(ownerUuid))
                .sorted(Comparator.comparingLong(ClaimRecord::createdAt).reversed())
                .collect(Collectors.toCollection(ArrayList::new));
    }

    public synchronized boolean hasClaims(UUID ownerUuid) {
        return claims.values().stream().anyMatch(claim -> claim.ownerUuid().equals(ownerUuid));
    }

    public synchronized boolean hasItemClaimForListing(String listingId) {
        return claims.values().stream()
                .anyMatch(claim -> claim.type() == ClaimType.ITEM && listingId != null && listingId.equals(claim.listingId()));
    }
}
