package com.example.backend.orders.model;

import java.util.Date;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

import com.example.backend.users.model.UserEntity;
import com.example.backend.core.model.BaseEntity;
import com.example.backend.ordersbooks.model.OrderBookEntity;

import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;

@Entity
@Table(name = "orders")
public class OrderEntity extends BaseEntity {
    @ManyToOne
    @JoinColumn(name = "userId", nullable = false)
    private UserEntity user;
    @Column(nullable = false)
    private Date date = new Date();
    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    @OrderBy("id ASC")
    private Set<OrderBookEntity> orderBooks = new HashSet<>();

    public OrderEntity() {
    }

    public UserEntity getUser() {
        return user;
    }

    public void setUser(UserEntity user) {
        this.user = user;
        if (!user.getOrders().contains(this)) {
            user.getOrders().add(this);
        }
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Set<OrderBookEntity> getOrderBooks() {
        return orderBooks;
    }

    public void addBook(OrderBookEntity orderBook) {
        if (orderBook.getOrder() != this) {
            orderBook.setOrder(this);
        }
        orderBooks.add(orderBook);
    }

    public void deleteBook(OrderBookEntity orderBook) {
        if (orderBook.getOrder() != this) {
            return;
        }
        orderBooks.remove(orderBook);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, user.getId(), date);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null || getClass() != obj.getClass())
            return false;
        final OrderEntity other = (OrderEntity) obj;
        return Objects.equals(other.getId(), id)
                && Objects.equals(other.getUser().getId(), user.getId())
                && Objects.equals(other.getDate(), date);
    }
}
