package com.ttstd.signaling.model;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

import java.time.Instant;

/**
 * 一次性配对码：用于被控端向主控端「授权绑定」。
 *
 * <p>流程：被控端生成配对码（明文仅回显一次）→ 主控端输入码 → 服务端校验并创建绑定。
 * 配对码存其 SHA-256 摘要，明文不落库；设有有效期、使用次数与错误尝试上限，防爆破。
 */
@Entity
@Table(name = "pairing_code")
public class PairingCode {

    @Id
    @Column(name = "code_hash", length = 64, nullable = false)
    private String codeHash;

    @Column(name = "device_uid", length = 48, nullable = false)
    private String deviceUid;

    @Column(name = "attempts", nullable = false)
    private int attempts = 0;

    @Column(name = "used", nullable = false)
    private boolean used = false;

    @Column(name = "expires_at", nullable = false)
    private Instant expiresAt;

    @Column(name = "created_at", nullable = false)
    private Instant createdAt = Instant.now();

    protected PairingCode() {
    }

    public PairingCode(String codeHash, String deviceUid, Instant expiresAt) {
        this.codeHash = codeHash;
        this.deviceUid = deviceUid;
        this.expiresAt = expiresAt;
        this.createdAt = Instant.now();
    }

    public String getCodeHash() { return codeHash; }
    public String getDeviceUid() { return deviceUid; }
    public int getAttempts() { return attempts; }
    public void setAttempts(int attempts) { this.attempts = attempts; }
    public boolean isUsed() { return used; }
    public void setUsed(boolean used) { this.used = used; }
    public Instant getExpiresAt() { return expiresAt; }
    public Instant getCreatedAt() { return createdAt; }

    public boolean isExpired() {
        return Instant.now().isAfter(expiresAt);
    }
}
