"""Custom polygons

Revision ID: f67c2bcbfcfa
Revises: c408dad8b7ed
Create Date: 2025-08-11 12:23:33.198154

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from geoalchemy2 import Geometry

# revision identifiers, used by Alembic.
revision = 'f67c2bcbfcfa'
down_revision = 'c408dad8b7ed'
branch_labels = None
depends_on = None


def upgrade():
    # Rename custom_point_groups to custom_groups, so it's clear the table is linked to custom_points and custom_polygons
    op.drop_constraint(constraint_name='custom_points_custom_point_group_id_fkey', table_name='custom_points')
    op.drop_constraint(constraint_name="custom_point_groups_name_key", table_name="custom_point_groups")
    op.create_unique_constraint('custom_groups_name_key', 'custom_point_groups', ['name'])
    op.alter_column('custom_points', 'custom_point_group_id', new_column_name='custom_group_id')
    op.rename_table('custom_point_groups', 'custom_groups')
    op.create_foreign_key(
        constraint_name='custom_group_id',
        source_table='custom_points', referent_table='custom_groups',
        local_cols=['custom_group_id'], remote_cols=['id']
    )

    op.create_table(
        'custom_polygons',
        sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
        sa.Column('custom_group_id', sa.Integer(), nullable=False),
        sa.Column('reference', sa.String(), nullable=True),
        sa.Column('created_at', sa.TIMESTAMP(), nullable=False),
        sa.Column('updated_at', sa.TIMESTAMP(), nullable=False),
        sa.Column('geometry', Geometry(geometry_type='POLYGON', srid=4326, from_text='ST_GeomFromEWKT'), nullable=False),

        sa.ForeignKeyConstraint(['custom_group_id'], ['custom_groups.id'], ),
        sa.PrimaryKeyConstraint('id')
    )

def downgrade():
    op.drop_table('custom_polygons')

    op.drop_constraint(constraint_name='custom_group_id', table_name='custom_points')
    op.alter_column('custom_points', 'custom_group_id', new_column_name='custom_point_group_id')
    op.rename_table('custom_groups', 'custom_point_groups')
    op.create_foreign_key(
        constraint_name='custom_points_custom_point_group_id_fkey',
        source_table='custom_points', referent_table='custom_point_groups',
        local_cols=['custom_point_group_id'], remote_cols=['id']
    )
