"use strict";

module.exports = {
  async up(queryInterface, Sequelize) {
    // falukant_data.character.reputation (integer, default random 20..80)
    // Wichtig: Schema explizit angeben
    // Vorgehen:
    // - Spalte anlegen (falls noch nicht vorhanden)
    // - bestehende Zeilen initialisieren (random 20..80)
    // - DEFAULT setzen (random 20..80)
    // - NOT NULL + CHECK 0..100 erzwingen
    await queryInterface.sequelize.query(`
      DO $$
      BEGIN
        IF NOT EXISTS (
          SELECT 1
          FROM information_schema.columns
          WHERE table_schema = 'falukant_data'
            AND table_name = 'character'
            AND column_name = 'reputation'
        ) THEN
          ALTER TABLE falukant_data."character"
          ADD COLUMN reputation integer;
        END IF;
      END$$;
    `);

    // Backfill: nur NULLs initialisieren (damit bestehende Werte nicht überschrieben werden)
    await queryInterface.sequelize.query(`
      UPDATE falukant_data."character"
      SET reputation = (floor(random()*61)+20)::int
      WHERE reputation IS NULL;
    `);

    // DEFAULT + NOT NULL (nach Backfill)
    await queryInterface.sequelize.query(`
      ALTER TABLE falukant_data."character"
      ALTER COLUMN reputation SET DEFAULT (floor(random()*61)+20)::int;
    `);
    await queryInterface.sequelize.query(`
      ALTER TABLE falukant_data."character"
      ALTER COLUMN reputation SET NOT NULL;
    `);

    // Enforce 0..100 at DB level (percent)
    // (IF NOT EXISTS pattern, because deployments can be re-run)
    await queryInterface.sequelize.query(`
      DO $$
      BEGIN
        IF NOT EXISTS (
          SELECT 1
          FROM pg_constraint c
          JOIN pg_class t ON t.oid = c.conrelid
          JOIN pg_namespace n ON n.oid = t.relnamespace
          WHERE c.conname = 'character_reputation_0_100_chk'
            AND n.nspname = 'falukant_data'
            AND t.relname = 'character'
        ) THEN
          ALTER TABLE falukant_data."character"
          ADD CONSTRAINT character_reputation_0_100_chk
          CHECK (reputation >= 0 AND reputation <= 100);
        END IF;
      END$$;
    `);
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.sequelize.query(`
      ALTER TABLE falukant_data."character"
      DROP CONSTRAINT IF EXISTS character_reputation_0_100_chk;
    `);
    await queryInterface.sequelize.query(`
      ALTER TABLE falukant_data."character"
      DROP COLUMN IF EXISTS reputation;
    `);
  },
};


