use loco_rs::schema::*;
use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> {
        create_table(
            m,
            "account_cart_items",
            &[
                ("id", ColType::PkAuto),
                ("variant_id", ColType::Integer),
                ("quantity", ColType::Integer),
            ],
            &[("user", "")],
        )
        .await?;

        m.create_foreign_key(
            ForeignKey::create()
                .name("fk-account_cart_items-variant_id-to-product_variants")
                .from(Alias::new("account_cart_items"), Alias::new("variant_id"))
                .to(Alias::new("product_variants"), Alias::new("id"))
                .on_delete(ForeignKeyAction::Cascade)
                .on_update(ForeignKeyAction::NoAction)
                .to_owned(),
        )
        .await?;

        m.create_index(
            Index::create()
                .name("idx_account_cart_items_user_variant_unique")
                .table(Alias::new("account_cart_items"))
                .col(Alias::new("user_id"))
                .col(Alias::new("variant_id"))
                .unique()
                .to_owned(),
        )
        .await
    }

    async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
        drop_table(m, "account_cart_items").await
    }
}
