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.time.LocalDate;
import java.time.LocalDateTime;

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

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

    @ManyToOne(fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne(fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name = "car_id")
    private Car car;

    /** Assigned driver for with-driver bookings. */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "driver_id")
    private Driver driver;

    @ColumnDefault("false")
    @Builder.Default
    private boolean withDriver = false;

    @NotNull
    private LocalDate pickupDate;

    @NotNull
    private LocalDate returnDate;

    @NotBlank
    private String pickupLocation;

    @NotBlank
    private String dropLocation;

    /* ---------- Period & charge breakdown ---------- */

    @Enumerated(EnumType.STRING)
    @ColumnDefault("'DAY'")
    @Builder.Default
    private RentalUnit rentalUnit = RentalUnit.DAY;

    /** Number of billed periods (days or months). */
    @ColumnDefault("1")
    @Builder.Default
    private int quantity = 1;

    private BigDecimal vehicleCharge;
    private BigDecimal driverCharge;
    private BigDecimal taxPercent;
    private BigDecimal taxAmount;

    @Column(nullable = false)
    private BigDecimal totalAmount;

    /* ---------- Revenue attribution ---------- */

    @Enumerated(EnumType.STRING)
    private CarOwnership revenueOwner;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "vendor_id")
    private Vendor vendor;

    private BigDecimal commissionPercent;
    private BigDecimal commissionAmount;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private BookingStatus status;

    @Column(nullable = false, updatable = false)
    private LocalDateTime createdAt;

    @PrePersist
    void onCreate() {
        if (createdAt == null) createdAt = LocalDateTime.now();
        if (status == null) status = BookingStatus.PENDING;
    }
}
