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 Role and Permission
 * 
 * Represents which permissions are assigned to which roles.
 * Example: Role "TENANT_ADMIN" has permissions ["tenant:read", "tenant:write", "user:read"]
 */
@Entity
@Table(name = "role_permissions",
       uniqueConstraints = @UniqueConstraint(columnNames = {"role_id", "permission_id"}))
@TenantSchemaEntity("RBAC role-permission assignments shared between admin and tenant databases")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class RolePermission {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    /**
     * Role that has this permission
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "role_id", nullable = false)
    private Role role;
    
    /**
     * Permission assigned to the role
     */
    @ManyToOne(fetch = FetchType.EAGER) // EAGER for permission details
    @JoinColumn(name = "permission_id", nullable = false)
    private Permission permission;
    
    /**
     * When this permission was assigned to the role
     */
    @CreationTimestamp
    @Column(nullable = false, updatable = false)
    private LocalDateTime assignedAt;
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof RolePermission)) return false;
        RolePermission that = (RolePermission) o;
        return role.getId().equals(that.role.getId()) && 
               permission.getId().equals(that.permission.getId());
    }
    
    @Override
    public int hashCode() {
        return java.util.Objects.hash(role.getId(), permission.getId());
    }
}
