'use strict';

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

/**
 * Sync all 11 element type defaults with correct sort_order.
 * This migration ensures all element types exist in element_type_defaults
 * and backfills any missing project_element_defaults for existing projects.
 */
module.exports = {
  async up(queryInterface, Sequelize) {
    const now = new Date();

    // Define all 11 element types with correct sort_order
    const DEFAULT_ELEMENT_TYPES = [
      {
        element_type: 'navigation_next',
        name: 'Navigation Forward Button',
        sort_order: 1,
        default_settings_json: {
          label: 'Navigation: Forward',
          navLabel: 'Forward',
          navType: 'forward',
          navDisabled: false,
          transitionReverseMode: 'auto_reverse',
          transitionDurationSec: 0.7,
          appearDelaySec: 0,
          appearDurationSec: null,
        },
      },
      {
        element_type: 'navigation_prev',
        name: 'Navigation Back Button',
        sort_order: 2,
        default_settings_json: {
          label: 'Navigation: Back',
          navLabel: 'Back',
          navType: 'back',
          navDisabled: false,
          transitionReverseMode: 'auto_reverse',
          transitionDurationSec: 0.7,
          appearDelaySec: 0,
          appearDurationSec: null,
        },
      },
      {
        element_type: 'tooltip',
        name: 'Tooltip',
        sort_order: 3,
        default_settings_json: {
          label: 'Tooltip',
          tooltipTitle: 'Tooltip title',
          tooltipText: 'Tooltip text',
          appearDelaySec: 0,
          appearDurationSec: null,
        },
      },
      {
        element_type: 'description',
        name: 'Description',
        sort_order: 4,
        default_settings_json: {
          label: 'Description',
          descriptionTitle: 'TITLE',
          descriptionText: '',
          descriptionTitleFontSize: '48px',
          descriptionTextFontSize: '36px',
          descriptionTitleFontFamily: 'inherit',
          descriptionTextFontFamily: 'inherit',
          descriptionTitleColor: '#000000',
          descriptionTextColor: '#4B5563',
          descriptionBackgroundColor: 'transparent',
          appearDelaySec: 0,
          appearDurationSec: null,
        },
      },
      {
        element_type: 'gallery',
        name: 'Gallery',
        sort_order: 5,
        default_settings_json: {
          label: 'Gallery',
          galleryCards: [{ imageUrl: '', title: 'Card 1', description: '' }],
          appearDelaySec: 0,
          appearDurationSec: null,
        },
      },
      {
        element_type: 'carousel',
        name: 'Carousel',
        sort_order: 6,
        default_settings_json: {
          label: 'Carousel',
          carouselSlides: [{ imageUrl: '', caption: 'Slide 1' }],
          carouselPrevIconUrl: '',
          carouselNextIconUrl: '',
          appearDelaySec: 0,
          appearDurationSec: null,
        },
      },
      {
        element_type: 'video_player',
        name: 'Video Player',
        sort_order: 7,
        default_settings_json: {
          label: 'Video Player',
          mediaUrl: '',
          mediaAutoplay: true,
          mediaLoop: true,
          mediaMuted: true,
          appearDelaySec: 0,
          appearDurationSec: null,
        },
      },
      {
        element_type: 'audio_player',
        name: 'Audio Player',
        sort_order: 8,
        default_settings_json: {
          label: 'Audio Player',
          mediaUrl: '',
          mediaAutoplay: true,
          mediaLoop: true,
          mediaMuted: false,
          appearDelaySec: 0,
          appearDurationSec: null,
        },
      },
      {
        element_type: 'spot',
        name: 'Hotspot',
        sort_order: 9,
        default_settings_json: {
          label: 'Hotspot',
          iconUrl: '',
          appearDelaySec: 0,
          appearDurationSec: null,
        },
      },
      {
        element_type: 'logo',
        name: 'Logo',
        sort_order: 10,
        default_settings_json: {
          label: 'Logo',
          iconUrl: '',
          backgroundImageUrl: '',
          appearDelaySec: 0,
          appearDurationSec: null,
        },
      },
      {
        element_type: 'popup',
        name: 'Popup',
        sort_order: 11,
        default_settings_json: {
          label: 'Popup',
          iconUrl: '',
          popupTitle: '',
          popupContent: '',
          appearDelaySec: 0,
          appearDurationSec: null,
        },
      },
    ];

    console.log('Syncing all 11 element type defaults...');

    // Track inserted/updated global defaults for backfill
    const globalDefaultIds = new Map();

    // For each element type: insert if not exists, update sort_order if wrong
    for (const elementType of DEFAULT_ELEMENT_TYPES) {
      const [existing] = await queryInterface.sequelize.query(
        `SELECT id, sort_order 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) {
        // Insert new element type
        const newId = uuidv4();
        await queryInterface.bulkInsert('element_type_defaults', [
          {
            id: newId,
            element_type: elementType.element_type,
            name: elementType.name,
            sort_order: elementType.sort_order,
            settings_json: JSON.stringify(elementType.default_settings_json),
            createdAt: now,
            updatedAt: now,
          },
        ]);
        globalDefaultIds.set(elementType.element_type, newId);
        console.log(
          `Inserted: ${elementType.element_type} (sort_order: ${elementType.sort_order})`,
        );
      } else {
        globalDefaultIds.set(elementType.element_type, existing.id);
        // Update sort_order if different
        if (existing.sort_order !== elementType.sort_order) {
          await queryInterface.sequelize.query(
            `UPDATE element_type_defaults
             SET sort_order = :sort_order, "updatedAt" = :now
             WHERE id = :id`,
            {
              replacements: {
                sort_order: elementType.sort_order,
                now,
                id: existing.id,
              },
            },
          );
          console.log(
            `Updated sort_order for ${elementType.element_type}: ${existing.sort_order} -> ${elementType.sort_order}`,
          );
        } else {
          console.log(
            `Already exists: ${elementType.element_type} (sort_order: ${elementType.sort_order})`,
          );
        }
      }
    }

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

    console.log(
      `Backfilling missing project_element_defaults for ${projects.length} projects...`,
    );

    // Get all global defaults for backfill
    const globalDefaults = await queryInterface.sequelize.query(
      `SELECT id, element_type, name, sort_order, settings_json
       FROM element_type_defaults
       WHERE "deletedAt" IS NULL`,
      { type: Sequelize.QueryTypes.SELECT },
    );

    let backfillCount = 0;

    // 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,
            },
          ]);
          backfillCount++;
        }
      }
    }

    console.log(`Backfilled ${backfillCount} project element defaults.`);
    console.log('Sync complete.');
  },

  async down(_queryInterface, _Sequelize) {
    // This migration is safe - it only adds missing data
    // No destructive down migration needed
    console.log(
      'No down migration needed - this migration only adds missing data.',
    );
  },
};
