// migration: 024_product_channels_attributes
// Adds sales channels, featured flag, and attribute tags to the catalog_products table

/** @param {import('node-pg-migrate').MigrationBuilder} pgm */
exports.up = (pgm) => {
  // Add channels column
  pgm.sql(`
    ALTER TABLE catalog_products
    ADD COLUMN IF NOT EXISTS channels TEXT NOT NULL DEFAULT 'all'
      CHECK (channels IN ('online', 'offline', 'all'))
  `);

  // Add featured column
  pgm.sql(`
    ALTER TABLE catalog_products
    ADD COLUMN IF NOT EXISTS featured BOOLEAN NOT NULL DEFAULT FALSE
  `);

  // Add attributes column (stored as JSONB array of strings)
  pgm.sql(`
    ALTER TABLE catalog_products
    ADD COLUMN IF NOT EXISTS attributes JSONB NOT NULL DEFAULT '[]'::jsonb
  `);

  // Add offer_cents and cost_cents to pricing_variant_prices
  pgm.sql(`
    ALTER TABLE pricing_variant_prices
    ADD COLUMN IF NOT EXISTS offer_cents INTEGER,
    ADD COLUMN IF NOT EXISTS cost_cents INTEGER
  `);

  // Create index for featured products (common query)
  pgm.sql(`
    CREATE INDEX IF NOT EXISTS catalog_products_featured_idx
    ON catalog_products (featured) WHERE featured = TRUE
  `);
};

/** @param {import('node-pg-migrate').MigrationBuilder} pgm */
exports.down = (pgm) => {
  pgm.sql(`ALTER TABLE catalog_products DROP COLUMN IF EXISTS channels`);
  pgm.sql(`ALTER TABLE catalog_products DROP COLUMN IF EXISTS featured`);
  pgm.sql(`ALTER TABLE catalog_products DROP COLUMN IF EXISTS attributes`);
  pgm.sql(`ALTER TABLE pricing_variant_prices DROP COLUMN IF EXISTS offer_cents`);
  pgm.sql(`ALTER TABLE pricing_variant_prices DROP COLUMN IF EXISTS cost_cents`);
  pgm.sql(`DROP INDEX IF EXISTS catalog_products_featured_idx`);
};
