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(
                r#"
CREATE TABLE ap_deliveries (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    activity_id INTEGER NOT NULL,
    signer_actor_id INTEGER NOT NULL,
    inbox_url TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'pending',
    attempts INTEGER NOT NULL DEFAULT 0,
    next_attempt_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
    last_error TEXT,
    UNIQUE (activity_id, inbox_url),
    FOREIGN KEY (activity_id) REFERENCES ap_activities(id) ON DELETE CASCADE,
    FOREIGN KEY (signer_actor_id) REFERENCES ap_actors(id) ON DELETE CASCADE
);
CREATE INDEX index_ap_deliveries_on_status_and_next_attempt ON ap_deliveries (status, next_attempt_at);
"#,
            )
            .await?;
        Ok(())
    }

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