"""Add notification_types and notification_preferences tables.

Creates tables for the notification preference system:
- notification_types: registered notification types from plugins
- notification_preferences: per-user opt-in/opt-out for notification types

Also seeds the 10 mail plugin notification types.

Revision ID: 0017_notification_preferences
Revises: 0016_plugin_is_core
Create Date: 2026-07-15
"""

from __future__ import annotations

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql


# revision identifiers, used by Alembic.
revision: str = "0017_notification_preferences"
down_revision: Union[str, None] = "0016_plugin_is_core"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


MAIL_NOTIFICATION_TYPES = [
    {"type_key": "mail_new", "label": "Neue E-Mail empfangen", "description": "Benachrichtigung bei neuen E-Mails", "is_enabled_by_default": True},
    {"type_key": "mail_error", "label": "IMAP-Verbindungsfehler", "description": "Fehler bei der Verbindung zum Mailserver", "is_enabled_by_default": True},
    {"type_key": "mail_auth", "label": "IMAP-Login-Fehler", "description": "Anmeldung am Mailserver fehlgeschlagen", "is_enabled_by_default": True},
    {"type_key": "mail_quota", "label": "Postfach fast voll", "description": "Warnung bei hohem Postfach-Füllstand", "is_enabled_by_default": True},
    {"type_key": "mail_sync_error", "label": "Sync-Fehler", "description": "Synchronisierung fehlgeschlagen", "is_enabled_by_default": True},
    {"type_key": "mail_sent", "label": "E-Mail gesendet", "description": "Bestätigung beim Senden einer E-Mail", "is_enabled_by_default": False},
    {"type_key": "mail_send_error", "label": "SMTP-Sendefehler", "description": "E-Mail konnte nicht gesendet werden", "is_enabled_by_default": True},
    {"type_key": "mail_draft", "label": "Entwurf gespeichert", "description": "Bestätigung beim Speichern eines Entwurfs", "is_enabled_by_default": False},
    {"type_key": "mail_account", "label": "Account deaktiviert", "description": "Warnung bei deaktiviertem Mail-Account", "is_enabled_by_default": True},
    {"type_key": "mail_folder", "label": "Ordner erstellt/gelöscht", "description": "Bestätigung bei Ordner-Operationen", "is_enabled_by_default": False},
]


def upgrade() -> None:
    # notification_types table
    op.create_table(
        "notification_types",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column("type_key", sa.String(20), nullable=False, unique=True),
        sa.Column("plugin_name", sa.String(100), nullable=False),
        sa.Column("category", sa.String(50), nullable=False, server_default="general"),
        sa.Column("label", sa.String(200), nullable=False),
        sa.Column("description", sa.Text(), nullable=True),
        sa.Column("is_enabled_by_default", sa.Boolean(), nullable=False, server_default=sa.text("true")),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
    )
    op.create_index("ix_notification_types_key", "notification_types", ["type_key"])

    # notification_preferences table
    op.create_table(
        "notification_preferences",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column("tenant_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False),
        sa.Column("user_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
        sa.Column("type_key", sa.String(20), nullable=False),
        sa.Column("is_enabled", sa.Boolean(), nullable=False, server_default=sa.text("true")),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.UniqueConstraint("user_id", "type_key", name="uq_notif_pref_user_type"),
    )
    op.create_index("ix_notif_prefs_user", "notification_preferences", ["user_id"])
    op.create_index("ix_notif_prefs_tenant", "notification_preferences", ["tenant_id"])

    # Seed mail plugin notification types
    for nt in MAIL_NOTIFICATION_TYPES:
        op.execute(
            sa.text(
                "INSERT INTO notification_types (id, type_key, plugin_name, category, label, description, is_enabled_by_default) "
                "VALUES (gen_random_uuid(), :type_key, 'mail', 'mail', :label, :description, :is_enabled_by_default)"
            ).bindparams(
                type_key=nt["type_key"],
                label=nt["label"],
                description=nt["description"],
                is_enabled_by_default=nt["is_enabled_by_default"],
            )
        )


def downgrade() -> None:
    op.drop_index("ix_notif_prefs_tenant", table_name="notification_preferences")
    op.drop_index("ix_notif_prefs_user", table_name="notification_preferences")
    op.drop_table("notification_preferences")
    op.drop_index("ix_notification_types_key", table_name="notification_types")
    op.drop_table("notification_types")
