"""Add groups and group_members tables.

Revision ID: c4e812fb3a01
Revises: b78571ae9e00
Create Date: 2026-04-23 19:00:00.000000
"""

from __future__ import annotations

import sqlalchemy as sa
from alembic import op

revision = "c4e812fb3a01"
down_revision = "b78571ae9e00"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.execute("""
    CREATE TABLE IF NOT EXISTS groups (
        id UUID PRIMARY KEY,
        name VARCHAR(128) NOT NULL,
        description TEXT,
        organization_id UUID REFERENCES organizations(id),
        created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
    )
    """)
    op.execute("CREATE INDEX IF NOT EXISTS ix_groups_organization_id ON groups (organization_id)")

    op.execute("""
    CREATE TABLE IF NOT EXISTS group_members (
        id UUID PRIMARY KEY,
        group_id UUID NOT NULL REFERENCES groups(id),
        identity_id UUID REFERENCES duniter_identities(id),
        display_name VARCHAR(128) NOT NULL,
        added_at TIMESTAMPTZ NOT NULL DEFAULT now()
    )
    """)
    op.execute("CREATE INDEX IF NOT EXISTS ix_group_members_group_id ON group_members (group_id)")


def downgrade() -> None:
    op.drop_index("ix_group_members_group_id", table_name="group_members")
    op.drop_table("group_members")
    op.drop_index("ix_groups_organization_id", table_name="groups")
    op.drop_table("groups")
