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> {
        // Table for tracking outbound Offers to remote trackers (round-trip client side).
        //
        // When a local user opens a ticket or merge request on a remote forge,
        // we create a row here with status 'pending', record the Offer activity,
        // and deliver it. When the remote tracker Accepts or Rejects, we update
        // the status and (for Accept) the assigned_url from the Accept.result field.
        manager
            .create_table(
                Table::create()
                    .table(ApRemoteTickets::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(ApRemoteTickets::Id)
                            .integer()
                            .not_null()
                            .auto_increment()
                            .primary_key(),
                    )
                    .col(
                        ColumnDef::new(ApRemoteTickets::Uuid)
                            .uuid()
                            .not_null()
                            .unique_key(),
                    )
                    .col(
                        ColumnDef::new(ApRemoteTickets::AuthorId)
                            .integer()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(ApRemoteTickets::Kind)
                            .string_len(16)
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(ApRemoteTickets::TrackerUrl)
                            .string_len(512)
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(ApRemoteTickets::OfferActivityUrl)
                            .string_len(512)
                            .not_null()
                            .unique_key(),
                    )
                    .col(
                        ColumnDef::new(ApRemoteTickets::Status)
                            .string_len(16)
                            .not_null()
                            .default("pending"),
                    )
                    .col(ColumnDef::new(ApRemoteTickets::AssignedUrl).string_len(512))
                    .col(
                        ColumnDef::new(ApRemoteTickets::Summary)
                            .string_len(255)
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(ApRemoteTickets::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_ap_remote_tickets_author_id")
                            .from(ApRemoteTickets::Table, ApRemoteTickets::AuthorId)
                            .to(Users::Table, Users::Id)
                            .on_delete(ForeignKeyAction::Cascade),
                    )
                    .to_owned(),
            )
            .await?;

        // Index for querying by author (user's outgoing tickets/MRs)
        manager
            .create_index(
                Index::create()
                    .name("idx_ap_remote_tickets_author_id")
                    .table(ApRemoteTickets::Table)
                    .col(ApRemoteTickets::AuthorId)
                    .to_owned(),
            )
            .await?;

        // Index for querying by status (pending/accepted/rejected)
        manager
            .create_index(
                Index::create()
                    .name("idx_ap_remote_tickets_status")
                    .table(ApRemoteTickets::Table)
                    .col(ApRemoteTickets::Status)
                    .to_owned(),
            )
            .await?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(ApRemoteTickets::Table).to_owned())
            .await?;

        Ok(())
    }
}

#[derive(Iden)]
enum ApRemoteTickets {
    Table,
    Id,
    Uuid,
    AuthorId,
    Kind,
    TrackerUrl,
    OfferActivityUrl,
    Status,
    AssignedUrl,
    Summary,
    CreatedAt,
}

#[derive(Iden)]
enum Users {
    Table,
    Id,
}
