package com.mvrent.carrental.model;

import jakarta.persistence.*;
import jakarta.validation.constraints.*;
import lombok.*;

import java.util.HashSet;
import java.util.Set;

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

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

    @Column(unique = true, nullable = false)
    @NotBlank
    @Size(min = 3, max = 50)
    private String username;

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

    // Set programmatically (encoded) by UserService/registration, not bound from the form.
    @Column(nullable = false)
    private String password;

    @NotBlank
    private String fullName;

    private String phone;

    private String licenseNumber;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private Role role;

    /** Set for ROLE_VENDOR portal users — links the login to its vendor. */
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "vendor_id")
    private Vendor vendor;

    /** Set for ROLE_DRIVER portal users — links the login to its driver record. */
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "driver_id")
    private Driver driver;

    /** Customer segment (master category of type CUSTOMER); optional. */
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "customer_category_id")
    private Category customerCategory;

    /** Granular staff capabilities; empty for customers/vendors. */
    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "user_permissions", joinColumns = @JoinColumn(name = "user_id"))
    @Enumerated(EnumType.STRING)
    @Column(name = "permission")
    @Builder.Default
    private Set<Permission> permissions = new HashSet<>();

    @Builder.Default
    private boolean enabled = true;
}
