package com.saas.admin.entity;

import com.saas.shared.annotation.TenantSchemaEntity;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;

import java.time.LocalDateTime;

/**
 * Junction table for many-to-many relationship between User and Role
 * 
 * Represents which roles are assigned to which users.
 * Example: User "john@example.com" has roles ["TENANT_ADMIN", "VOIP_MANAGER"]
 * 
 * A user can have multiple roles, and each role can be assigned to multiple users.
 */
@Entity
@Table(name = "user_roles",
       uniqueConstraints = @UniqueConstraint(columnNames = {"user_id", "role_id"}))
@TenantSchemaEntity("RBAC user-role assignments shared between admin and tenant databases")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class UserRole {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    /**
     * User who has this role
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", nullable = false)
    private User user;
    
    /**
     * Role assigned to the user
     */
    @ManyToOne(fetch = FetchType.EAGER) // EAGER for role details
    @JoinColumn(name = "role_id", nullable = false)
    private Role role;
    
    /**
     * When this role was assigned to the user
     */
    @CreationTimestamp
    @Column(nullable = false, updatable = false)
    private LocalDateTime assignedAt;
    
    /**
     * Admin who assigned this role (optional, for audit trail)
     */
    @Column(name = "assigned_by")
    private String assignedBy;
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof UserRole)) return false;
        UserRole that = (UserRole) o;
        return user.getId().equals(that.user.getId()) && 
               role.getId().equals(that.role.getId());
    }
    
    @Override
    public int hashCode() {
        return java.util.Objects.hash(user.getId(), role.getId());
    }
}
