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> {
        // plugin_entities 新增 manifest_id 列 — 避免跨插件查询时 JOIN plugins 表
        manager
            .get_connection()
            .execute_unprepared(
                r#"
ALTER TABLE plugin_entities
ADD COLUMN IF NOT EXISTS manifest_id TEXT NOT NULL DEFAULT '';

ALTER TABLE plugin_entities
ADD COLUMN IF NOT EXISTS is_public BOOLEAN NOT NULL DEFAULT false;

-- 回填 manifest_id（从 plugins.manifest_json 提取 metadata.id）
UPDATE plugin_entities pe
SET manifest_id = COALESCE(p.manifest_json->'metadata'->>'id', '')
FROM plugins p
WHERE pe.plugin_id = p.id AND pe.deleted_at IS NULL;

-- 跨插件实体查找索引
CREATE INDEX IF NOT EXISTS idx_plugin_entities_cross_ref
ON plugin_entities (manifest_id, entity_name, tenant_id)
WHERE deleted_at IS NULL;
"#,
            )
            .await?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .get_connection()
            .execute_unprepared(
                r#"
DROP INDEX IF EXISTS idx_plugin_entities_cross_ref;
ALTER TABLE plugin_entities DROP COLUMN IF EXISTS is_public;
ALTER TABLE plugin_entities DROP COLUMN IF EXISTS manifest_id;
"#,
            )
            .await?;

        Ok(())
    }
}
