"""PostgreSQL addon definition."""

from __future__ import annotations

from typing import Any

from kuberoku.addons._types import AddonDef
from kuberoku.branding import TOOL_NAME


def _pg_env(secret_name: str, user: str, password: str, db: str) -> list[dict[str, Any]]:
    """Build container env list for PostgreSQL using Secret refs."""
    return [
        {
            "name": "POSTGRES_USER",
            "valueFrom": {
                "secretKeyRef": {"name": secret_name, "key": "username"},
            },
        },
        {
            "name": "POSTGRES_PASSWORD",
            "valueFrom": {
                "secretKeyRef": {"name": secret_name, "key": "password"},
            },
        },
        {
            "name": "POSTGRES_DB",
            "valueFrom": {
                "secretKeyRef": {"name": secret_name, "key": "database"},
            },
        },
        {
            "name": "PGDATA",
            "value": "/var/lib/postgresql/data/pgdata",
        },
    ]


POSTGRES = AddonDef(
    type_name="postgres",
    image="postgres:16",
    port=5432,
    protocol="TCP",
    default_cpu="250m",
    default_memory="256Mi",
    default_storage="1Gi",
    needs_storage=True,
    storage_optional=False,
    needs_auth=True,
    env_key="DATABASE_URL",
    url_template="postgres://{user}:{password}@{host}:{port}/{db}",
    data_dir="/var/lib/postgresql/data",
    volume_name="pgdata",
    readiness_probe={
        "exec": {
            "command": ["pg_isready", "-U", TOOL_NAME],
        },
        "initialDelaySeconds": 5,
        "periodSeconds": 5,
        "timeoutSeconds": 3,
    },
    exec_command=["psql", "-U", "{user}", "-d", "{db}"],
    backup_command=["pg_dump", "-U", "{user}", "{db}"],
    restore_command=["psql", "-U", "{user}", "-d", "{db}"],
    container_env_builder=_pg_env,
    versions={"15": "postgres:15", "16": "postgres:16", "17": "postgres:17"},
    default_version="16",
    migration_paths={
        "15": ("16",),
        "16": ("15", "17"),
        "17": ("16",),
    },
    migrate_dump_command=[
        "pg_dump",
        "--clean",
        "--if-exists",
        "--no-owner",
        "--no-privileges",
        "-U",
        "{user}",
        "-f",
        "/tmp/backup.sql",
        "{db}",
    ],
    migrate_restore_command=[
        "psql",
        "-U",
        "{user}",
        "-d",
        "{db}",
        "-f",
        "/tmp/backup.sql",
    ],
    migrate_dump_file="/tmp/backup.sql",
)
