"""API key authentication dependency for FastAPI."""

from __future__ import annotations

import hashlib
import sqlite3

from fastapi import Depends, Header, HTTPException

from .db import get_db


def hash_api_key(raw_key: str) -> str:
    """SHA-256 hash of the raw API key, returned as hex."""
    return hashlib.sha256(raw_key.encode()).hexdigest()


def require_api_key(
    x_api_key: str = Header(..., description="ProofTrail API key"),
    conn: sqlite3.Connection = Depends(get_db),
) -> dict:
    """Validate API key and return the key row as a dict."""
    key_hash = hash_api_key(x_api_key)
    row = conn.execute(
        "SELECT id, org_name, is_active FROM api_keys WHERE key_hash = ?",
        (key_hash,),
    ).fetchone()

    if row is None:
        raise HTTPException(status_code=401, detail="Invalid API key")
    if not row["is_active"]:
        raise HTTPException(status_code=401, detail="API key is deactivated")

    return {"id": row["id"], "org_name": row["org_name"]}
