"""Create invitations collection with TTL index."""

from app.migrations.migrator import Migration


class Migration(Migration):

    def __init__(self):
        super().__init__()
        self.version = "2026-04-28-000002"
        self.description = "Create invitations collection with TTL index"

    async def up(self) -> None:
        validator = {
            "$jsonSchema": {
                "bsonType": "object",
                "required": ["email", "organization_id", "role_in_org", "token_hash", "invited_by_user_id", "expires_at"],
                "properties": {
                    "email": {"bsonType": "string"},
                    "organization_id": {"bsonType": "string"},
                    "role_in_org": {"enum": ["owner", "admin", "manager", "member", "viewer"]},
                    "token_hash": {"bsonType": "string"},
                    "invited_by_user_id": {"bsonType": "string"},
                    "expires_at": {"bsonType": "date"},
                    "accepted_at": {"bsonType": ["date", "null"]},
                    "revoked_at": {"bsonType": ["date", "null"]},
                    "target_team_ids": {"bsonType": ["array"]},
                    "created_at": {"bsonType": "date"},
                },
            }
        }

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

        col = self.db["invitations"]

        # Non-unique index on token_hash for fast lookup
        await col.create_index([("token_hash", 1)], name="token_hash_idx")
        await col.create_index([("organization_id", 1)], name="org_idx")
        await col.create_index([("email", 1)], name="email_idx")

        # TTL: expire documents 30 days AFTER expires_at (keeps audit trail)
        # MongoDB TTL works by setting expireAfterSeconds on a date field
        # We use a computed field "purge_at" = expires_at + 30d to keep accepted/revoked records
        # For simplicity: use expires_at with 2592000s (30d) offset
        await col.create_index(
            [("expires_at", 1)],
            expireAfterSeconds=30 * 24 * 60 * 60,
            name="expires_ttl",
        )

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

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