"""caldav_configs tables + fix smtp_configs missing FK

Revision ID: 0007_caldav_and_fixes
Revises: 0006_smtp
Create Date: 2026-03-27

Fixes:
- smtp_configs.company_id had no FK constraint (orphaned records possible)
- caldav_company_configs and caldav_user_configs were created via create_all,
  not tracked by Alembic — now formally managed here
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID


revision = "0007_caldav_and_fixes"
down_revision = "0006_smtp"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # ── Fix 1: smtp_configs missing FK ───────────────────────────────────────
    # The FK was omitted in 0006_smtp. Add it now.
    op.create_foreign_key(
        "fk_smtp_configs_company_id",
        "smtp_configs", "companies",
        ["company_id"], ["id"],
        ondelete="CASCADE",
    )

    # ── Fix 2: caldav tables (created via create_all, now Alembic-managed) ───
    # Use checkfirst=True so fresh installs that don't have the tables yet
    # get them created, while existing installs skip creation silently.
    bind = op.get_bind()

    if not bind.dialect.has_table(bind, "caldav_company_configs"):
        op.create_table(
            "caldav_company_configs",
            sa.Column("id", UUID(as_uuid=True), primary_key=True),
            sa.Column("company_id", UUID(as_uuid=True),
                      sa.ForeignKey("companies.id", ondelete="CASCADE"),
                      nullable=False, unique=True),
            sa.Column("enabled", sa.Boolean(), nullable=False, server_default="false"),
            sa.Column("principal_url", sa.Text(), nullable=False, server_default=""),
            sa.Column("calendar_url", sa.Text(), nullable=True),
            sa.Column("username", sa.String(255), nullable=False, server_default=""),
            sa.Column("password_encrypted", sa.Text(), nullable=False, server_default=""),
            sa.Column("calendar_display_name", sa.String(255), nullable=False, server_default=""),
            sa.Column("verify_ssl", sa.Boolean(), nullable=False, server_default="true"),
            sa.Column("last_error", sa.Text(), nullable=True),
            sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now()),
            sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now()),
        )
        op.create_index("ix_caldav_company_configs_company_id", "caldav_company_configs", ["company_id"])

    if not bind.dialect.has_table(bind, "caldav_user_configs"):
        op.create_table(
            "caldav_user_configs",
            sa.Column("id", UUID(as_uuid=True), primary_key=True),
            sa.Column("user_id", UUID(as_uuid=True),
                      sa.ForeignKey("users.id", ondelete="CASCADE"),
                      nullable=False, unique=True),
            sa.Column("enabled", sa.Boolean(), nullable=False, server_default="false"),
            sa.Column("principal_url", sa.Text(), nullable=False, server_default=""),
            sa.Column("calendar_url", sa.Text(), nullable=True),
            sa.Column("username", sa.String(255), nullable=False, server_default=""),
            sa.Column("password_encrypted", sa.Text(), nullable=False, server_default=""),
            sa.Column("calendar_display_name", sa.String(255), nullable=False, server_default=""),
            sa.Column("verify_ssl", sa.Boolean(), nullable=False, server_default="true"),
            sa.Column("last_error", sa.Text(), nullable=True),
            sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now()),
            sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now()),
        )
        op.create_index("ix_caldav_user_configs_user_id", "caldav_user_configs", ["user_id"])


def downgrade() -> None:
    # Remove the smtp FK (restores state to 0006_smtp)
    op.drop_constraint("fk_smtp_configs_company_id", "smtp_configs", type_="foreignkey")

    # Drop caldav tables only if they were created by this migration
    # (i.e., on a fresh install path — existing installs: tables stay)
    op.drop_index("ix_caldav_user_configs_user_id", table_name="caldav_user_configs")
    op.drop_table("caldav_user_configs")
    op.drop_index("ix_caldav_company_configs_company_id", table_name="caldav_company_configs")
    op.drop_table("caldav_company_configs")
