import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddForeignKeys1690 implements MigrationInterface {
  async up(queryRunner: QueryRunner): Promise<void> {
    // 1. User与Workspace的关联
    await queryRunner.query(`
      ALTER TABLE "user"
      ADD CONSTRAINT "fk_user_workspace"
      FOREIGN KEY ("workspaceId")
      REFERENCES "workspace"("id")
      ON DELETE CASCADE
    `);

    // 2. AiConfig与Workspace的关联
    await queryRunner.query(`
      ALTER TABLE "ai_config"
      ADD CONSTRAINT "fk_ai_config_workspace"
      FOREIGN KEY ("workspaceId")
      REFERENCES "workspace"("id")
      ON DELETE CASCADE
    `);

    // 3. Project与Workspace的关联
    await queryRunner.query(`
      ALTER TABLE "project"
      ADD CONSTRAINT "fk_project_workspace"
      FOREIGN KEY ("workspaceId")
      REFERENCES "workspace"("id")
      ON DELETE CASCADE
    `);

    // 4. PluginConfig与Workspace的关联
    await queryRunner.query(`
      ALTER TABLE "plugin_config"
      ADD CONSTRAINT "fk_plugin_config_workspace"
      FOREIGN KEY ("workspaceId")
      REFERENCES "workspace"("id")
      ON DELETE CASCADE
    `);
  }

  async down(queryRunner: QueryRunner): Promise<void> {
    // 删除外键约束
    const foreignKeys = [
      'fk_user_workspace',
      'fk_ai_config_workspace',
      'fk_project_workspace',
      'fk_plugin_config_workspace'
    ];

    for (const fk of foreignKeys) {
      await queryRunner.query(
        `ALTER TABLE ${fk.split('_').slice(2).join('_')} DROP CONSTRAINT ${fk}`
      );
    }
  }
}