/**
 * Admin API Token 管理
 * 表：admin_api_token（id, name, token_hash, permissions, created_by, created_at, last_used_at, expires_at, is_active）
 */
import { query } from "./db";
import { randomBytes } from "crypto";

// Token 前缀（用于识别）
const TOKEN_PREFIX = "adm_tok_";

export interface ApiToken {
  id: number;
  name: string;
  token_prefix: string;
  permissions: string[];
  created_by: number;
  created_at: Date;
  last_used_at: Date | null;
  expires_at: Date | null;
  is_active: boolean;
}

/** 生成随机 token（返回明文，用于一次显示） */
export function generateToken(): string {
  return TOKEN_PREFIX + randomBytes(24).toString("hex");
}

/** 计算 token 的 SHA-256 哈希 */
export async function hashToken(token: string): Promise<string> {
  const { createHash } = await import("crypto");
  return createHash("sha256").update(token).digest("hex");
}

/** 列出所有 token（不返回 hash） */
export async function listApiTokens(): Promise<ApiToken[]> {
  const result = await query<{
    id: number;
    name: string;
    token_prefix: string;
    permissions: string[];
    created_by: number;
    created_at: Date;
    last_used_at: Date | null;
    expires_at: Date | null;
    is_active: boolean;
  }>(
    `SELECT id, name, token_prefix, permissions, created_by, created_at, last_used_at, expires_at, is_active
     FROM admin_api_token ORDER BY created_at DESC`
  );
  return result.rows;
}

/** 根据 token_hash 验证 token（用于中间件） */
export async function verifyToken(token: string): Promise<
  { valid: true; tokenId: number; permissions: string[] } |
  { valid: false }
> {
  const hash = await hashToken(token);
  const result = await query<{
    id: number;
    token_prefix: string;
    permissions: string[];
    is_active: boolean;
    expires_at: Date | null;
    last_used_at: Date | null;
  }>(
    `SELECT id, token_prefix, permissions, is_active, expires_at, last_used_at
     FROM admin_api_token WHERE token_hash = $1`,
    [hash]
  );

  if (!result.rows.length) return { valid: false };

  const row = result.rows[0];
  if (!row.is_active) return { valid: false };
  if (row.expires_at && new Date(row.expires_at) < new Date()) return { valid: false };

  // 更新 last_used_at
  await query(
    `UPDATE admin_api_token SET last_used_at = NOW() WHERE id = $1`,
    [row.id]
  );

  return { valid: true, tokenId: row.id, permissions: row.permissions || [] };
}

/** 创建 token（返回明文，仅此一次） */
export async function createApiToken(params: {
  name: string;
  token: string;
  permissions: string[];
  createdBy: number;
  expiresAt?: Date | null;
}): Promise<{ token: string; id: number }> {
  const hash = await hashToken(params.token);
  const result = await query<{ id: number }>(
    `INSERT INTO admin_api_token (name, token_hash, token_prefix, permissions, created_by, expires_at, is_active)
     VALUES ($1, $2, $3, $4, $5, $6, true)
     RETURNING id`,
    [
      params.name,
      hash,
      TOKEN_PREFIX + params.token.slice(TOKEN_PREFIX.length, TOKEN_PREFIX.length + 8),
      params.permissions,
      params.createdBy,
      params.expiresAt || null,
    ]
  );
  return { token: params.token, id: result.rows[0].id };
}

/** 删除 token */
export async function deleteApiToken(id: number): Promise<void> {
  await query(`DELETE FROM admin_api_token WHERE id = $1`, [id]);
}
