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> {
        // Create the patch_proposals table
        manager
            .create_table(
                Table::create()
                    .table(PatchProposals::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(PatchProposals::Id)
                            .integer()
                            .not_null()
                            .auto_increment()
                            .primary_key(),
                    )
                    .col(
                        ColumnDef::new(PatchProposals::Uuid)
                            .uuid()
                            .not_null()
                            .unique_key(),
                    )
                    .col(
                        ColumnDef::new(PatchProposals::RepositoryId)
                            .integer()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(PatchProposals::CreatorId)
                            .integer()
                            .not_null(),
                    )
                    .col(ColumnDef::new(PatchProposals::Number).integer().not_null())
                    .col(
                        ColumnDef::new(PatchProposals::Summary)
                            .string_len(255)
                            .not_null(),
                    )
                    .col(ColumnDef::new(PatchProposals::Description).text())
                    .col(
                        ColumnDef::new(PatchProposals::SourceRef)
                            .string_len(255)
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(PatchProposals::TargetBranch)
                            .string_len(255)
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(PatchProposals::Status)
                            .string_len(16)
                            .not_null()
                            .default("draft"),
                    )
                    .col(
                        ColumnDef::new(PatchProposals::MergePolicy)
                            .string_len(32)
                            .not_null()
                            .default("prefer-fast-forward"),
                    )
                    .col(
                        ColumnDef::new(PatchProposals::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(PatchProposals::UpdatedAt)
                            .timestamp_with_time_zone()
                            .not_null(),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_patch_proposals_repository_id")
                            .from(PatchProposals::Table, PatchProposals::RepositoryId)
                            .to(Repositories::Table, Repositories::Id)
                            .on_delete(ForeignKeyAction::Cascade),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_patch_proposals_creator_id")
                            .from(PatchProposals::Table, PatchProposals::CreatorId)
                            .to(Users::Table, Users::Id)
                            .on_delete(ForeignKeyAction::Cascade),
                    )
                    .to_owned(),
            )
            .await?;

        // Add unique constraint for (repository_id, number) to ensure patch
        // numbers are unique per repository
        manager
            .create_index(
                Index::create()
                    .name("uq_patch_proposals_repository_number")
                    .table(PatchProposals::Table)
                    .col(PatchProposals::RepositoryId)
                    .col(PatchProposals::Number)
                    .unique()
                    .to_owned(),
            )
            .await?;

        // Add unique constraint for (repository_id, source_ref) to ensure
        // source refs are unique per repository
        manager
            .create_index(
                Index::create()
                    .name("uq_patch_proposals_repository_source_ref")
                    .table(PatchProposals::Table)
                    .col(PatchProposals::RepositoryId)
                    .col(PatchProposals::SourceRef)
                    .unique()
                    .to_owned(),
            )
            .await?;

        // Create indexes for commonly queried fields
        manager
            .create_index(
                Index::create()
                    .name("idx_patch_proposals_repository_id")
                    .table(PatchProposals::Table)
                    .col(PatchProposals::RepositoryId)
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_patch_proposals_creator_id")
                    .table(PatchProposals::Table)
                    .col(PatchProposals::CreatorId)
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_patch_proposals_status")
                    .table(PatchProposals::Table)
                    .col(PatchProposals::RepositoryId)
                    .col(PatchProposals::Status)
                    .to_owned(),
            )
            .await?;

        // Add next_patch_number and default_merge_policy to repositories table
        manager
            .get_connection()
            .execute_unprepared(
                "ALTER TABLE repositories ADD COLUMN next_patch_number integer NOT NULL DEFAULT 1",
            )
            .await?;

        manager
            .get_connection()
            .execute_unprepared(
                "ALTER TABLE repositories ADD COLUMN default_merge_policy varchar(32) NOT NULL DEFAULT 'prefer-fast-forward'",
            )
            .await?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .get_connection()
            .execute_unprepared("ALTER TABLE repositories DROP COLUMN default_merge_policy")
            .await?;

        manager
            .get_connection()
            .execute_unprepared("ALTER TABLE repositories DROP COLUMN next_patch_number")
            .await?;

        manager
            .drop_table(Table::drop().table(PatchProposals::Table).to_owned())
            .await?;

        Ok(())
    }
}

#[derive(Iden)]
enum PatchProposals {
    Table,
    Id,
    Uuid,
    RepositoryId,
    CreatorId,
    Number,
    Summary,
    Description,
    SourceRef,
    TargetBranch,
    Status,
    MergePolicy,
    CreatedAt,
    UpdatedAt,
}

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

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