package de.htwsaar.webshop.repository.entities;

import de.htwsaar.webshop.model.OrderItemModel;
import jakarta.persistence.*;
import jakarta.validation.constraints.Min;
import lombok.*;
import org.hibernate.annotations.OnDelete;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
@Table(name = "Order_Items")
public class OrderItem {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    @Min(value = 1, message = "Amount must be at least 1")
    private Integer amount;

    @ManyToOne(fetch = FetchType.EAGER, optional = false, cascade = CascadeType.ALL, targetEntity = Order.class)
    @JoinColumn(name = "order_id", referencedColumnName = "id", nullable = false)
    @OnDelete(action = org.hibernate.annotations.OnDeleteAction.CASCADE)
    private Order order;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "article_id", referencedColumnName = "id", nullable = false)
    @OnDelete(action = org.hibernate.annotations.OnDeleteAction.SET_NULL)
    private Article article;

    public OrderItemModel toModel() {
        return new OrderItemModel(id, amount, article.getUuid());
    }

    public Integer getPrice() {
        return amount * (article.getPrice100() * (100-article.getDiscount100()))/100;
    }
}
