import { MigrationInterface, QueryRunner } from "typeorm";

export class AddDefaultTenant1772329237979 implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<void> {
        // 1. Insert "Default" tenant if it doesn't exist.
        // We use a predefined UUID or let the DB generate it.
        // Assuming Postgres/MySQL compatible uuid generation isn't strictly standard here,
        // we'll insert and get the ID back, or use a workaround for SQLite if it's SQLite.
        // Actually, since this is a TypeORM setup, we can use standard SQL.

        // This is a bit tricky to write purely in SQL that works across all DBs (SQLite/Postgres/MySQL)
        // without knowing the exact DB.  AuraK seems to use SQLite locally by default.
        // First, check if there's any record in the tenant table.
        const tenants = await queryRunner.query(`SELECT id FROM "tenant" WHERE "name" = 'Default'`);
        let defaultTenantId;

        if (tenants && tenants.length > 0) {
            defaultTenantId = tenants[0].id;
        } else {
            // Create it with a JS generated UUID to be database agnostic
            const crypto = require('crypto');
            defaultTenantId = crypto.randomUUID();
            const now = new Date().toISOString();
            await queryRunner.query(
                `INSERT INTO "tenant" (id, name, description, "createdAt", "updatedAt") VALUES (?, ?, ?, ?, ?)`,
                [defaultTenantId, 'Default', 'Default tenant created by migration', now, now]
            );

            // Create tenant settings
            const settingsId = crypto.randomUUID();
            await queryRunner.query(
                `INSERT INTO "tenant_setting" (id, "tenantId", "createdAt", "updatedAt") VALUES (?, ?, ?, ?)`,
                [settingsId, defaultTenantId, now, now]
            );
        }

        // 2. Assign the Default tenant to all relevant existing records that have no tenantId
        const tablesToUpdate = ['user', 'knowledge_base', 'knowledge_group', 'search_history', 'note', 'model_config'];

        for (const table of tablesToUpdate) {
            // Check if table exists first (some might be missing if DB is fresh)
            try {
                await queryRunner.query(`UPDATE "${table}" SET "tenantId" = ? WHERE "tenantId" IS NULL`, [defaultTenantId]);
            } catch (e) {
                console.warn(`Could not update table ${table}, it might not exist or the tenantId column might not exist yet.`);
            }
        }
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        // We don't necessarily want to delete the tenant data in a down migration
        // as it would orphan all the records or require setting them to NULL.
        // But for completeness, we can set them back to NULL.

        const tablesToUpdate = ['user', 'knowledge_base', 'knowledge_group', 'search_history', 'note', 'model_config'];
        for (const table of tablesToUpdate) {
            try {
                await queryRunner.query(`UPDATE "${table}" SET "tenantId" = NULL`);
            } catch (e) {
                // Ignore
            }
        }
    }

}
