use sea_orm_migration::prelude::*;

use crate::m20220101_000002_create_enums::RecurrenceType;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(RecurrenceRule::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(RecurrenceRule::Id)
                            .uuid()
                            .primary_key()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(RecurrenceRule::Type)
                            .custom(RecurrenceType::Type)
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(RecurrenceRule::Interval)
                            .integer()
                            .not_null()
                            .default(1),
                    )
                    .col(ColumnDef::new(RecurrenceRule::ByWeekday).integer().null())
                    .col(ColumnDef::new(RecurrenceRule::ByMonthday).integer().null())
                    .col(
                        ColumnDef::new(RecurrenceRule::Timezone)
                            .string()
                            .not_null()
                            .default("Asia/Shanghai"),
                    )
                    .col(
                        ColumnDef::new(RecurrenceRule::CreatedAt)
                            .timestamp()
                            .not_null()
                            .extra("DEFAULT NOW()"),
                    )
                    .col(
                        ColumnDef::new(RecurrenceRule::UpdatedAt)
                            .timestamp()
                            .not_null(),
                    )
                    .to_owned(),
            )
            .await
    }

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

#[derive(DeriveIden)]
enum RecurrenceRule {
    Table,
    Id,
    Type,
    Interval,
    ByWeekday,
    ByMonthday,
    Timezone,
    CreatedAt,
    UpdatedAt,
}
