'use strict';

const { v4: uuidv4 } = require('uuid');

/**
 * Add missing element type defaults (spot, logo, popup)
 * These were missing from the original DEFAULT_ROWS and need to be added to existing databases.
 * Also backfills project_element_defaults for existing projects.
 */
module.exports = {
  async up(queryInterface, Sequelize) {
    const now = new Date();

    // Define the missing element types
    const missingTypes = [
      {
        id: uuidv4(),
        element_type: 'spot',
        name: 'Hotspot',
        sort_order: 9,
        settings_json: JSON.stringify({
          label: 'Hotspot',
          iconUrl: '',
          appearDelaySec: 0,
          appearDurationSec: null,
        }),
        createdAt: now,
        updatedAt: now,
      },
      {
        id: uuidv4(),
        element_type: 'logo',
        name: 'Logo',
        sort_order: 10,
        settings_json: JSON.stringify({
          label: 'Logo',
          iconUrl: '',
          backgroundImageUrl: '',
          appearDelaySec: 0,
          appearDurationSec: null,
        }),
        createdAt: now,
        updatedAt: now,
      },
      {
        id: uuidv4(),
        element_type: 'popup',
        name: 'Popup',
        sort_order: 11,
        settings_json: JSON.stringify({
          label: 'Popup',
          iconUrl: '',
          popupTitle: '',
          popupContent: '',
          appearDelaySec: 0,
          appearDurationSec: null,
        }),
        createdAt: now,
        updatedAt: now,
      },
    ];

    // Insert missing global defaults (skip if they already exist)
    for (const elementType of missingTypes) {
      const [existing] = await queryInterface.sequelize.query(
        `SELECT id FROM element_type_defaults WHERE element_type = :element_type AND "deletedAt" IS NULL`,
        {
          replacements: { element_type: elementType.element_type },
          type: Sequelize.QueryTypes.SELECT,
        },
      );

      if (!existing) {
        await queryInterface.bulkInsert('element_type_defaults', [elementType]);
        console.log(`Added global default for: ${elementType.element_type}`);
      } else {
        console.log(
          `Global default already exists for: ${elementType.element_type}`,
        );
      }
    }

    // Get all inserted/existing global defaults for the missing types
    const globalDefaults = await queryInterface.sequelize.query(
      `SELECT id, element_type, name, sort_order, settings_json
       FROM element_type_defaults
       WHERE element_type IN ('spot', 'logo', 'popup') AND "deletedAt" IS NULL`,
      { type: Sequelize.QueryTypes.SELECT },
    );

    // Get all projects
    const projects = await queryInterface.sequelize.query(
      `SELECT id FROM projects WHERE "deletedAt" IS NULL`,
      { type: Sequelize.QueryTypes.SELECT },
    );

    console.log(
      `Backfilling ${globalDefaults.length} element types to ${projects.length} projects...`,
    );

    // Backfill project_element_defaults for each project
    for (const project of projects) {
      for (const globalDefault of globalDefaults) {
        // Check if project already has this element type
        const [existing] = await queryInterface.sequelize.query(
          `SELECT id FROM project_element_defaults
           WHERE "projectId" = :projectId AND element_type = :element_type AND "deletedAt" IS NULL`,
          {
            replacements: {
              projectId: project.id,
              element_type: globalDefault.element_type,
            },
            type: Sequelize.QueryTypes.SELECT,
          },
        );

        if (!existing) {
          await queryInterface.bulkInsert('project_element_defaults', [
            {
              id: uuidv4(),
              projectId: project.id,
              element_type: globalDefault.element_type,
              name: globalDefault.name,
              sort_order: globalDefault.sort_order,
              settings_json: globalDefault.settings_json,
              source_element_id: globalDefault.id,
              snapshot_version: 1,
              createdAt: now,
              updatedAt: now,
            },
          ]);
        }
      }
    }

    console.log('Backfill complete.');
  },

  async down(queryInterface, _Sequelize) {
    // Remove the added element types from project_element_defaults
    await queryInterface.sequelize.query(
      `DELETE FROM project_element_defaults WHERE element_type IN ('spot', 'logo', 'popup')`,
    );

    // Remove from element_type_defaults
    await queryInterface.sequelize.query(
      `DELETE FROM element_type_defaults WHERE element_type IN ('spot', 'logo', 'popup')`,
    );
  },
};
