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> {
        // One shipping/contact profile per customer, used to prefill the
        // checkout form. `name`/`email` already live on `users`; this table
        // holds only the address + phone fields. `user` adds a user_id FK; the
        // unique index below makes the relationship 1:1.
        create_table(
            m,
            "customer_profiles",
            &[
                ("id", ColType::PkAuto),
                ("phone_prefix", ColType::StringNull),
                ("phone", ColType::StringNull),
                ("address", ColType::StringNull),
                ("city", ColType::StringNull),
                ("zip", ColType::StringNull),
                ("country", ColType::StringNull),
            ],
            &[("user", "")],
        )
        .await?;

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

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