// SPDX-FileCopyrightText: 2026 Ololduck <ololduck@vit.am> and contributors
//
// SPDX-License-Identifier: GPL-3.0-or-later

use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .get_connection()
            .execute_unprepared(
                "CREATE TABLE IF NOT EXISTS user_silences (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    blocker_id INTEGER NOT NULL,
                    blocked_user_id INTEGER,
                    blocked_remote_actor_id INTEGER,
                    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (blocker_id) REFERENCES users(id) ON DELETE CASCADE,
                    FOREIGN KEY (blocked_user_id) REFERENCES users(id) ON DELETE CASCADE,
                    FOREIGN KEY (blocked_remote_actor_id) REFERENCES ap_remote_actors(id) ON DELETE CASCADE,
                    UNIQUE (blocker_id, blocked_user_id),
                    UNIQUE (blocker_id, blocked_remote_actor_id),
                    CHECK (
                        (blocked_user_id IS NOT NULL AND blocked_remote_actor_id IS NULL) OR
                        (blocked_user_id IS NULL AND blocked_remote_actor_id IS NOT NULL)
                    )
                )",
            )
            .await?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .get_connection()
            .execute_unprepared("DROP TABLE IF EXISTS user_silences")
            .await?;

        Ok(())
    }
}
