package com.example.backend.ordersbooks.model;

import java.util.Objects;

import com.example.backend.books.model.BookEntity;
import com.example.backend.orders.model.OrderEntity;

import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.MapsId;
import jakarta.persistence.Table;

@Entity
@Table(name = "orders_books")
public class OrderBookEntity {
    @EmbeddedId
    private OrderBookId id = new OrderBookId();
    @ManyToOne
    @MapsId("orderId")
    @JoinColumn(name = "order_id")
    private OrderEntity order;
    @ManyToOne
    @MapsId("bookId")
    @JoinColumn(name = "book_id")
    private BookEntity book;
    @Column(nullable = false)
    private Integer count;

    public OrderBookEntity() {
    }

    public OrderBookEntity(OrderEntity order, BookEntity book, Integer count) {
        this.order = order;
        this.book = book;
        this.count = count;
    }

    public OrderBookId getId() {
        return id;
    }

    public void setId(OrderBookId id) {
        this.id = id;
    }

    public OrderEntity getOrder() {
        return order;
    }

    public void setOrder(OrderEntity order) {
        this.order = order;
        if (!order.getOrderBooks().contains(this)) {
            order.getOrderBooks().add(this);
        }
    }

    public BookEntity getBook() {
        return book;
    }

    public void setBook(BookEntity book) {
        this.book = book;
        if (!book.getOrderBooks().contains(this)) {
            book.getOrderBooks().add(this);
        }
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, order.getId(), book.getId(), count);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null || getClass() != obj.getClass())
            return false;
        OrderBookEntity other = (OrderBookEntity) obj;
        return Objects.equals(id, other.id)
                && Objects.equals(order.getId(), other.order.getId())
                && Objects.equals(book.getId(), other.book.getId())
                && count == other.count;
    }
}
