'use strict';

/**
 * Migration: Copy existing dev content to stage environment
 *
 * This migration initializes the stage environment for existing projects
 * by copying all dev content to stage. This establishes the new workflow
 * where constructor edits dev, then explicitly saves to stage.
 */
module.exports = {
  async up(queryInterface, Sequelize) {
    // Get all projects
    const projects = await queryInterface.sequelize.query(
      `SELECT id FROM projects WHERE "deletedAt" IS NULL`,
      { type: Sequelize.QueryTypes.SELECT },
    );

    if (!projects || projects.length === 0) {
      console.log('No projects found, skipping dev to stage copy');
      return;
    }

    for (const project of projects) {
      const projectId = project.id;

      // Check if stage content already exists
      const [stageCheck] = await queryInterface.sequelize.query(
        `SELECT COUNT(*)::int as count FROM tour_pages
         WHERE "projectId" = '${projectId}' AND environment = 'stage' AND "deletedAt" IS NULL`,
        { type: Sequelize.QueryTypes.SELECT },
      );

      if (stageCheck?.count > 0) {
        console.log(`Project ${projectId} already has stage content, skipping`);
        continue;
      }

      // Get dev pages count first
      const [devPageCount] = await queryInterface.sequelize.query(
        `SELECT COUNT(*)::int as count FROM tour_pages
         WHERE "projectId" = '${projectId}' AND environment = 'dev' AND "deletedAt" IS NULL`,
        { type: Sequelize.QueryTypes.SELECT },
      );

      if (!devPageCount || devPageCount.count === 0) {
        console.log(`Project ${projectId} has no dev content, skipping`);
        continue;
      }

      // Copy pages with direct INSERT...SELECT
      await queryInterface.sequelize.query(`
        INSERT INTO tour_pages
        (id, slug, name, sort_order, background_image_url, background_video_url, background_audio_url, background_loop, requires_auth, ui_schema_json, "projectId", environment, source_key, "createdAt", "updatedAt", "createdById", "updatedById")
        SELECT
          gen_random_uuid(),
          slug,
          name,
          sort_order,
          background_image_url,
          background_video_url,
          background_audio_url,
          background_loop,
          requires_auth,
          ui_schema_json,
          "projectId",
          'stage',
          id::text,
          NOW(),
          NOW(),
          "createdById",
          "updatedById"
        FROM tour_pages
        WHERE "projectId" = '${projectId}' AND environment = 'dev' AND "deletedAt" IS NULL
      `);

      // Copy transitions
      await queryInterface.sequelize.query(`
        INSERT INTO transitions
        (id, name, slug, video_url, audio_url, supports_reverse, duration_sec, "projectId", environment, source_key, "createdAt", "updatedAt", "createdById", "updatedById")
        SELECT
          gen_random_uuid(),
          name,
          slug,
          video_url,
          audio_url,
          supports_reverse,
          duration_sec,
          "projectId",
          'stage',
          id::text,
          NOW(),
          NOW(),
          "createdById",
          "updatedById"
        FROM transitions
        WHERE "projectId" = '${projectId}' AND environment = 'dev' AND "deletedAt" IS NULL
      `);

      // Copy audio tracks
      await queryInterface.sequelize.query(`
        INSERT INTO project_audio_tracks
        (id, name, slug, url, "loop", volume, sort_order, is_enabled, "projectId", environment, source_key, "createdAt", "updatedAt", "createdById", "updatedById")
        SELECT
          gen_random_uuid(),
          name,
          slug,
          url,
          "loop",
          volume,
          sort_order,
          is_enabled,
          "projectId",
          'stage',
          id::text,
          NOW(),
          NOW(),
          "createdById",
          "updatedById"
        FROM project_audio_tracks
        WHERE "projectId" = '${projectId}' AND environment = 'dev' AND "deletedAt" IS NULL
      `);

      // Copy page elements using a subquery to map page IDs
      await queryInterface.sequelize.query(`
        INSERT INTO page_elements
        (id, element_type, name, sort_order, is_visible, x_percent, y_percent, width_percent, height_percent, rotation_deg, style_json, content_json, "pageId", "createdAt", "updatedAt", "createdById", "updatedById")
        SELECT
          gen_random_uuid(),
          pe.element_type,
          pe.name,
          pe.sort_order,
          pe.is_visible,
          pe.x_percent,
          pe.y_percent,
          pe.width_percent,
          pe.height_percent,
          pe.rotation_deg,
          pe.style_json,
          pe.content_json,
          stage_page.id,
          NOW(),
          NOW(),
          pe."createdById",
          pe."updatedById"
        FROM page_elements pe
        INNER JOIN tour_pages dev_page ON pe."pageId" = dev_page.id
        INNER JOIN tour_pages stage_page ON stage_page.source_key = dev_page.id::text AND stage_page.environment = 'stage'
        WHERE dev_page."projectId" = '${projectId}'
          AND dev_page.environment = 'dev'
          AND dev_page."deletedAt" IS NULL
          AND pe."deletedAt" IS NULL
      `);

      // Copy page links using subqueries to map page and transition IDs
      await queryInterface.sequelize.query(`
        INSERT INTO page_links
        (id, trigger_selector, external_url, "from_pageId", "to_pageId", "transitionId", "createdAt", "updatedAt", "createdById", "updatedById")
        SELECT
          gen_random_uuid(),
          pl.trigger_selector,
          pl.external_url,
          stage_from.id,
          stage_to.id,
          stage_transition.id,
          NOW(),
          NOW(),
          pl."createdById",
          pl."updatedById"
        FROM page_links pl
        INNER JOIN tour_pages dev_from ON pl."from_pageId" = dev_from.id
        INNER JOIN tour_pages stage_from ON stage_from.source_key = dev_from.id::text AND stage_from.environment = 'stage'
        LEFT JOIN tour_pages dev_to ON pl."to_pageId" = dev_to.id
        LEFT JOIN tour_pages stage_to ON stage_to.source_key = dev_to.id::text AND stage_to.environment = 'stage'
        LEFT JOIN transitions dev_transition ON pl."transitionId" = dev_transition.id
        LEFT JOIN transitions stage_transition ON stage_transition.source_key = dev_transition.id::text AND stage_transition.environment = 'stage'
        WHERE dev_from."projectId" = '${projectId}'
          AND dev_from.environment = 'dev'
          AND dev_from."deletedAt" IS NULL
          AND pl."deletedAt" IS NULL
      `);

      console.log(`Copied dev content to stage for project ${projectId}`);
    }

    console.log('Successfully copied dev content to stage for all projects');
  },

  async down(queryInterface, _Sequelize) {
    // Delete all stage content that has a source_key (meaning it was created by this migration)
    await queryInterface.sequelize.query(
      `DELETE FROM page_links WHERE "from_pageId" IN (SELECT id FROM tour_pages WHERE environment = 'stage' AND source_key IS NOT NULL)`,
    );
    await queryInterface.sequelize.query(
      `DELETE FROM page_elements WHERE "pageId" IN (SELECT id FROM tour_pages WHERE environment = 'stage' AND source_key IS NOT NULL)`,
    );
    await queryInterface.sequelize.query(
      `DELETE FROM tour_pages WHERE environment = 'stage' AND source_key IS NOT NULL`,
    );
    await queryInterface.sequelize.query(
      `DELETE FROM transitions WHERE environment = 'stage' AND source_key IS NOT NULL`,
    );
    await queryInterface.sequelize.query(
      `DELETE FROM project_audio_tracks WHERE environment = 'stage' AND source_key IS NOT NULL`,
    );

    console.log('Removed stage content created by migration');
  },
};
