"""Create memberships collection with index and schema validator."""

from app.migrations.migrator import Migration


class Migration(Migration):

    def __init__(self):
        super().__init__()
        self.version = "2026-04-28-000000"
        self.description = "Create memberships collection"

    async def up(self) -> None:
        validator = {
            "$jsonSchema": {
                "bsonType": "object",
                "required": ["user_id", "organization_id", "role_in_org"],
                "properties": {
                    "user_id": {"bsonType": "string"},
                    "organization_id": {"bsonType": "string"},
                    "role_in_org": {
                        "enum": ["owner", "admin", "manager", "member", "viewer"],
                    },
                    "created_at": {"bsonType": "date"},
                    "updated_at": {"bsonType": "date"},
                    "created_by": {"bsonType": ["string", "null"]},
                },
            }
        }

        try:
            await self.db.create_collection(
                "memberships",
                validator=validator,
                validationLevel="moderate",
                validationAction="error",
            )
            print("✅ Created memberships collection")
        except Exception:
            # Collection may already exist
            try:
                await self.db.command({
                    "collMod": "memberships",
                    "validator": validator,
                    "validationLevel": "moderate",
                    "validationAction": "error",
                })
                print("✅ Updated memberships collection validator")
            except Exception as e:
                print(f"⚠️  Could not set validator: {e}")

        col = self.db["memberships"]
        await col.create_index(
            [("user_id", 1), ("organization_id", 1)],
            unique=True,
            name="user_org_unique",
        )
        await col.create_index([("organization_id", 1)], name="org_idx")
        await col.create_index([("user_id", 1)], name="user_idx")

        print(f"✅ Applied migration {self.version}: {self.description}")

    async def down(self) -> None:
        await self.db.drop_collection("memberships")
        print(f"⚠️  Rolled back migration {self.version}: dropped memberships collection")
