package com.saas.admin.entity;

import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;

/**
 * CallerIdMapping Entity
 * 
 * Maps specific caller phone numbers (From) to tenants for call forwarding scenarios
 * where the original destination number (To) is not owned by our platform.
 * 
 * Use Case:
 * - Client has existing phone number and forwards calls to Twilio/Telnyx
 * - We lose the "To" number context (it's the client's number, not in our phone_numbers table)
 * - This mapping allows tenant resolution based on the caller's number instead
 * 
 * Security:
 * - UNIQUE constraint on fromPhoneNumber prevents one caller from mapping to multiple tenants
 * - All CRUD operations are audited via @Auditable annotation in service layer
 * - Only SYSTEM_ADMIN can create/modify mappings
 */
@Entity
@Table(name = "caller_id_mappings", indexes = {
        @Index(name = "idx_from_phone_unique", columnList = "fromPhoneNumber", unique = true),
        @Index(name = "idx_tenant_id_caller", columnList = "tenantId")
})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class CallerIdMapping {

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

    /**
     * The caller's phone number (From field in webhooks)
     * MUST be unique - one caller can only belong to one tenant
     */
    @Column(nullable = false, unique = true, length = 50)
    private String fromPhoneNumber;

    /**
     * Tenant ID this caller belongs to
     */
    @Column(nullable = false, length = 100)
    private String tenantId;

    /**
     * Human-readable description of this mapping
     * Example: "Dr. Smith's forwarded mobile line"
     */
    @Column(length = 500)
    private String description;

    /**
     * Admin user ID who created this mapping (for audit trail)
     */
    @Column(nullable = false)
    private Long createdBy;

    /**
     * Whether this mapping is currently active
     */
    @Column(nullable = false)
    @Builder.Default
    private Boolean isActive = true;

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

    @UpdateTimestamp
    @Column(nullable = false)
    private LocalDateTime updatedAt;
}
