package com.yourname.premiumah.model;

import org.bukkit.inventory.ItemStack;

import java.util.Objects;
import java.util.UUID;

public final class Listing {
    private final String id;
    private final UUID sellerUuid;
    private final String sellerName;
    private final ItemStack item;
    private final double price;
    private final long createdAt;
    private final long expiresAt;
    private ListingStatus status;
    private UUID buyerUuid;
    private String buyerName;
    private long updatedAt;

    public Listing(String id,
                   UUID sellerUuid,
                   String sellerName,
                   ItemStack item,
                   double price,
                   long createdAt,
                   long expiresAt,
                   ListingStatus status,
                   UUID buyerUuid,
                   String buyerName,
                   long updatedAt) {
        this.id = Objects.requireNonNull(id, "id");
        this.sellerUuid = Objects.requireNonNull(sellerUuid, "sellerUuid");
        this.sellerName = Objects.requireNonNullElse(sellerName, "Unknown");
        this.item = Objects.requireNonNull(item, "item").clone();
        this.price = price;
        this.createdAt = createdAt;
        this.expiresAt = expiresAt;
        this.status = Objects.requireNonNull(status, "status");
        this.buyerUuid = buyerUuid;
        this.buyerName = buyerName;
        this.updatedAt = updatedAt;
    }

    public String id() {
        return id;
    }

    public UUID sellerUuid() {
        return sellerUuid;
    }

    public String sellerName() {
        return sellerName;
    }

    public ItemStack item() {
        return item.clone();
    }

    public ItemStack rawItem() {
        return item;
    }

    public double price() {
        return price;
    }

    public long createdAt() {
        return createdAt;
    }

    public long expiresAt() {
        return expiresAt;
    }

    public ListingStatus status() {
        return status;
    }

    public void status(ListingStatus status) {
        this.status = Objects.requireNonNull(status, "status");
        touch();
    }

    public UUID buyerUuid() {
        return buyerUuid;
    }

    public String buyerName() {
        return buyerName;
    }

    public long updatedAt() {
        return updatedAt;
    }

    public boolean isActive(long now) {
        return status == ListingStatus.ACTIVE && expiresAt > now;
    }

    public void soldTo(UUID buyerUuid, String buyerName) {
        this.status = ListingStatus.SOLD;
        this.buyerUuid = buyerUuid;
        this.buyerName = buyerName;
        touch();
    }

    private void touch() {
        this.updatedAt = System.currentTimeMillis();
    }
}
