/**
 * Catalog product and variant images.
 */

/** @param {import('node-pg-migrate').MigrationBuilder} pgm */
export const up = (pgm) => {
  pgm.sql(`
    CREATE TABLE catalog_product_images (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      product_id uuid NOT NULL REFERENCES catalog_products(id) ON DELETE CASCADE,
      variant_id uuid REFERENCES catalog_product_variants(id) ON DELETE CASCADE,
      url text NOT NULL,
      alt_text text NOT NULL,
      position integer NOT NULL DEFAULT 0,
      role text NOT NULL,
      created_at timestamptz NOT NULL DEFAULT now(),
      updated_at timestamptz NOT NULL DEFAULT now(),
      CONSTRAINT catalog_product_images_position_check CHECK (position >= 0),
      CONSTRAINT catalog_product_images_role_check CHECK (role IN ('main', 'gallery'))
    )
  `);
  pgm.sql(
    'CREATE INDEX catalog_product_images_product_scope_idx ON catalog_product_images (product_id, variant_id, position)',
  );
  pgm.sql(`
    CREATE UNIQUE INDEX catalog_product_images_product_main_unique
    ON catalog_product_images (product_id)
    WHERE variant_id IS NULL AND role = 'main'
  `);
  pgm.sql(`
    CREATE UNIQUE INDEX catalog_product_images_variant_main_unique
    ON catalog_product_images (variant_id)
    WHERE variant_id IS NOT NULL AND role = 'main'
  `);
  pgm.sql(`
    CREATE OR REPLACE FUNCTION catalog_product_image_variant_scope_check()
    RETURNS trigger AS $$
    BEGIN
      IF NEW.variant_id IS NOT NULL AND NOT EXISTS (
        SELECT 1 FROM catalog_product_variants v
        WHERE v.id = NEW.variant_id AND v.product_id = NEW.product_id
      ) THEN
        RAISE EXCEPTION 'catalog product image variant must belong to product';
      END IF;
      RETURN NEW;
    END;
    $$ LANGUAGE plpgsql
  `);
  pgm.sql(`
    CREATE TRIGGER catalog_product_images_variant_scope_check
    BEFORE INSERT OR UPDATE OF product_id, variant_id ON catalog_product_images
    FOR EACH ROW EXECUTE FUNCTION catalog_product_image_variant_scope_check()
  `);
};

/** @param {import('node-pg-migrate').MigrationBuilder} pgm */
export const down = (pgm) => {
  pgm.sql(
    'DROP TRIGGER IF EXISTS catalog_product_images_variant_scope_check ON catalog_product_images',
  );
  pgm.sql('DROP FUNCTION IF EXISTS catalog_product_image_variant_scope_check');
  pgm.sql('DROP TABLE IF EXISTS catalog_product_images');
};
