"""Admin endpoints for API key management."""

from __future__ import annotations

import hmac
import secrets
import sqlite3

from fastapi import APIRouter, Depends, Header, HTTPException

from ..auth import hash_api_key
from ..config import settings
from ..db import get_db
from ..models import CreateKeyRequest, CreateKeyResponse

router = APIRouter(prefix="/admin")


def require_admin_secret(
    x_admin_secret: str = Header(..., description="Admin secret"),
) -> None:
    if not hmac.compare_digest(x_admin_secret, settings.admin_secret):
        raise HTTPException(status_code=403, detail="Invalid admin secret")


@router.post("/api-keys", response_model=CreateKeyResponse, status_code=201)
def create_api_key(
    body: CreateKeyRequest,
    conn: sqlite3.Connection = Depends(get_db),
    _: None = Depends(require_admin_secret),
):
    raw_key = "pt_live_" + secrets.token_hex(16)
    key_id = "pk_" + secrets.token_hex(8)
    key_hash = hash_api_key(raw_key)

    conn.execute(
        "INSERT INTO api_keys (id, key_hash, org_name) VALUES (?, ?, ?)",
        (key_id, key_hash, body.org_name),
    )
    conn.commit()

    return CreateKeyResponse(id=key_id, api_key=raw_key, org_name=body.org_name)
