package com.gcsc.connection.apikey.entity;

import com.gcsc.connection.service.entity.SnpServiceApi;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

@Getter
@NoArgsConstructor(access = lombok.AccessLevel.PROTECTED)
@Entity
@Table(name = "snp_api_permission", schema = "common",
    uniqueConstraints = @UniqueConstraint(columnNames = {"api_key_id", "api_id"}))
public class SnpApiPermission {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "permission_id")
    private Long permissionId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "api_key_id", nullable = false)
    private SnpApiKey apiKey;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "api_id", nullable = false)
    private SnpServiceApi api;

    @Column(name = "is_active", nullable = false)
    private Boolean isActive = true;

    @Column(name = "granted_by")
    private Long grantedBy;

    @Column(name = "granted_at", nullable = false)
    private LocalDateTime grantedAt;

    @Column(name = "revoked_at")
    private LocalDateTime revokedAt;

    @Builder
    public SnpApiPermission(SnpApiKey apiKey, SnpServiceApi api, Boolean isActive,
                            Long grantedBy, LocalDateTime grantedAt) {
        this.apiKey = apiKey;
        this.api = api;
        this.isActive = isActive != null ? isActive : true;
        this.grantedBy = grantedBy;
        this.grantedAt = grantedAt != null ? grantedAt : LocalDateTime.now();
    }

    public void revoke() {
        this.isActive = false;
        this.revokedAt = LocalDateTime.now();
    }
}
