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> {
        // Following relationships: which local actors follow which remote
        // actors. This is the opposite direction of ap_followers.
        // follow_activity_id is our Follow activity's id, for matching
        // Accept/Reject. state tracks whether the follow is pending,
        // accepted, or rejected.
        manager
            .get_connection()
            .execute_unprepared(
                "CREATE TABLE IF NOT EXISTS ap_following (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    local_actor_id INTEGER NOT NULL,
                    remote_actor_id INTEGER NOT NULL,
                    follow_activity_id TEXT NOT NULL UNIQUE,
                    state TEXT NOT NULL DEFAULT 'pending',
                    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (local_actor_id) REFERENCES ap_actors(id) ON DELETE CASCADE,
                    FOREIGN KEY (remote_actor_id) REFERENCES ap_remote_actors(id) ON DELETE CASCADE,
                    UNIQUE (local_actor_id, remote_actor_id)
                )",
            )
            .await?;

        Ok(())
    }

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

        Ok(())
    }
}
