"""Ajoute la gestion métier des logements de fonction.

Revision ID: d5e9f0a1b2c3
Revises: c4d8e9f0a1b2
"""
from alembic import op
import sqlalchemy as sa

revision = "d5e9f0a1b2c3"
down_revision = "c4d8e9f0a1b2"
branch_labels = None
depends_on = None


def upgrade():
    op.create_table(
        "housing_units",
        sa.Column("id", sa.Integer(), nullable=False),
        sa.Column("name", sa.String(length=120), nullable=False),
        sa.Column("code", sa.String(length=40), nullable=True),
        sa.Column("building_id", sa.Integer(), nullable=False),
        sa.Column("housing_type", sa.String(length=40), nullable=False, server_default="fonction"),
        sa.Column("occupancy_status", sa.String(length=30), nullable=False, server_default="vacant"),
        sa.Column("occupant_name", sa.String(length=150), nullable=True),
        sa.Column("occupant_contact", sa.String(length=150), nullable=True),
        sa.Column("occupancy_start", sa.Date(), nullable=True),
        sa.Column("occupancy_end", sa.Date(), nullable=True),
        sa.Column("notes", sa.Text(), nullable=True),
        sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.true()),
        sa.Column("created_at", sa.DateTime(), nullable=True),
        sa.Column("updated_at", sa.DateTime(), nullable=True),
        sa.ForeignKeyConstraint(["building_id"], ["buildings.id"]),
        sa.PrimaryKeyConstraint("id"), sa.UniqueConstraint("code"),
    )
    op.create_index("ix_housing_units_building_id", "housing_units", ["building_id"])
    op.add_column("rooms", sa.Column("housing_unit_id", sa.Integer(), nullable=True))
    op.create_foreign_key("fk_rooms_housing_unit", "rooms", "housing_units", ["housing_unit_id"], ["id"])
    op.create_index("ix_rooms_housing_unit_id", "rooms", ["housing_unit_id"])


def downgrade():
    op.drop_index("ix_rooms_housing_unit_id", table_name="rooms")
    op.drop_constraint("fk_rooms_housing_unit", "rooms", type_="foreignkey")
    op.drop_column("rooms", "housing_unit_id")
    op.drop_table("housing_units")
