import { MigrationInterface, QueryRunner } from 'typeorm';

export class InitSchema1745000000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS \`user\` (
        \`id\` varchar(36) NOT NULL,
        \`email\` varchar(255) NOT NULL,
        \`passwordHash\` varchar(255) NOT NULL,
        \`isVerified\` tinyint NOT NULL DEFAULT 0,
        \`otpCode\` varchar(6) NULL,
        \`otpExpiresAt\` timestamp NULL,
        \`createdAt\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
        PRIMARY KEY (\`id\`),
        UNIQUE KEY \`IDX_user_email\` (\`email\`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);

    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS \`word\` (
        \`id\` varchar(36) NOT NULL,
        \`text\` varchar(255) NOT NULL,
        \`createdAt\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
        \`status\` varchar(20) NOT NULL DEFAULT 'active',
        \`ownerId\` varchar(36) NULL,
        PRIMARY KEY (\`id\`),
        UNIQUE KEY \`IDX_word_text_owner\` (\`text\`, \`ownerId\`),
        CONSTRAINT \`FK_word_owner\` FOREIGN KEY (\`ownerId\`) REFERENCES \`user\` (\`id\`) ON DELETE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);

    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS \`definition\` (
        \`id\` varchar(36) NOT NULL,
        \`text\` text NOT NULL,
        \`date\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
        \`context\` text NULL,
        \`word_id\` varchar(36) NULL,
        PRIMARY KEY (\`id\`),
        CONSTRAINT \`FK_definition_word\` FOREIGN KEY (\`word_id\`) REFERENCES \`word\` (\`id\`) ON DELETE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE IF EXISTS \`definition\``);
    await queryRunner.query(`DROP TABLE IF EXISTS \`word\``);
    await queryRunner.query(`DROP TABLE IF EXISTS \`user\``);
  }
}
