package de.htwsaar.webshop.repository.entities;

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

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@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.LAZY, optional = false, cascade = CascadeType.ALL, targetEntity = Order.class)
    @MapsId("order_id")
    @JoinColumn(name = "order_id", referencedColumnName = "id", nullable = false)
    @OnDelete(action = org.hibernate.annotations.OnDeleteAction.CASCADE)
    private Order order;

    @ManyToOne(fetch = FetchType.LAZY)
    @MapsId("articleId")
    @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());
    }
}
