package com.gcsc.connection.apikey.entity;

import com.gcsc.connection.common.entity.BaseEntity;
import com.gcsc.connection.user.entity.SnpUser;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
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 lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

@Getter
@NoArgsConstructor(access = lombok.AccessLevel.PROTECTED)
@Entity
@Table(name = "snp_api_key", schema = "common")
public class SnpApiKey extends BaseEntity {

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

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", nullable = false)
    private SnpUser user;

    @Column(name = "api_key", length = 128, nullable = false, unique = true)
    private String apiKey;

    @Column(name = "api_key_prefix", length = 10)
    private String apiKeyPrefix;

    @Column(name = "key_name", length = 200, nullable = false)
    private String keyName;

    @Enumerated(EnumType.STRING)
    @Column(name = "status", length = 20, nullable = false)
    private ApiKeyStatus status = ApiKeyStatus.PENDING;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approved_by")
    private SnpUser approvedBy;

    @Column(name = "approved_at")
    private LocalDateTime approvedAt;

    @Column(name = "expires_at")
    private LocalDateTime expiresAt;

    @Column(name = "last_used_at")
    private LocalDateTime lastUsedAt;

    @Column(name = "daily_request_limit")
    private Long dailyRequestLimit;

    @Builder
    public SnpApiKey(SnpUser user, String apiKey, String apiKeyPrefix, String keyName,
                     ApiKeyStatus status, SnpUser approvedBy, LocalDateTime approvedAt,
                     LocalDateTime expiresAt, Long dailyRequestLimit) {
        this.user = user;
        this.apiKey = apiKey;
        this.apiKeyPrefix = apiKeyPrefix;
        this.keyName = keyName;
        this.status = status != null ? status : ApiKeyStatus.PENDING;
        this.approvedBy = approvedBy;
        this.approvedAt = approvedAt;
        this.expiresAt = expiresAt;
        this.dailyRequestLimit = dailyRequestLimit;
    }

    public void revoke() {
        this.status = ApiKeyStatus.REVOKED;
    }

    public void updateLastUsedAt() {
        this.lastUsedAt = LocalDateTime.now();
    }

    public void activate(SnpUser approvedBy) {
        this.status = ApiKeyStatus.ACTIVE;
        this.approvedBy = approvedBy;
        this.approvedAt = LocalDateTime.now();
    }
}
