package com.mvrent.carrental.model;

import jakarta.persistence.*;
import jakarta.validation.constraints.*;
import lombok.*;
import org.hibernate.annotations.ColumnDefault;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Entity
@Table(name = "cars")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Car {

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

    @NotBlank
    private String make;

    @NotBlank
    private String model;

    @Column(unique = true, nullable = false)
    @NotBlank
    private String registrationNumber;

    /** Year the vehicle was registered, e.g. 2022. */
    private Integer yearOfRegistration;

    private String colour;

    @Enumerated(EnumType.STRING)
    @NotNull
    private CarType type;

    @Min(2)
    @Max(15)
    private int seats;

    @Enumerated(EnumType.STRING)
    private Transmission transmission;

    @Enumerated(EnumType.STRING)
    private FuelType fuelType;

    /** Feature tags such as AC, GPS, Sunroof, Bluetooth. */
    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "car_feature_tags", joinColumns = @JoinColumn(name = "car_id"))
    @Column(name = "tag")
    @Builder.Default
    private Set<String> featureTags = new HashSet<>();

    /* ---------- Rates ---------- */

    private BigDecimal hourlyRate;

    @NotNull
    @DecimalMin("0.0")
    private BigDecimal pricePerDay;   // daily rate

    private BigDecimal monthlyRate;

    /* ---------- Ownership & availability ---------- */

    @Enumerated(EnumType.STRING)
    @ColumnDefault("'OWNED'")
    @Builder.Default
    private CarOwnership ownership = CarOwnership.OWNED;

    /** Set when ownership = VENDOR. */
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "vendor_id")
    private Vendor vendor;

    /** Per-vehicle commission override; falls back to vendor/global when null. */
    private BigDecimal commissionPercentOverride;

    @ColumnDefault("1")
    @Builder.Default
    private int unitsTotal = 1;

    @Enumerated(EnumType.STRING)
    @ColumnDefault("'ACTIVE'")
    @Builder.Default
    private CarStatus status = CarStatus.ACTIVE;

    private String imageUrl;

    @Builder.Default
    private boolean available = true;

    /* ---------- Documents & photos ---------- */

    @OneToMany(mappedBy = "car", cascade = CascadeType.ALL, orphanRemoval = true)
    @OrderBy("expiryDate ASC")
    @Builder.Default
    private List<CarDocument> documents = new ArrayList<>();

    @OneToMany(mappedBy = "car", cascade = CascadeType.ALL, orphanRemoval = true)
    @OrderBy("sortOrder ASC")
    @Builder.Default
    private List<CarPhoto> photos = new ArrayList<>();

    /** Bookable only when listed and operationally active. */
    @Transient
    public boolean isBookable() {
        return available && status == CarStatus.ACTIVE;
    }
}
