/**
 * Catalog core product tables. Module-owned naming: catalog_<table>.
 */

/** @param {import('node-pg-migrate').MigrationBuilder} pgm */
export const up = (pgm) => {
  pgm.sql(`
    CREATE TABLE catalog_products (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      name text NOT NULL,
      slug text NOT NULL UNIQUE,
      description text,
      state text NOT NULL DEFAULT 'draft',
      seo_title text,
      seo_description text,
      created_at timestamptz NOT NULL DEFAULT now(),
      updated_at timestamptz NOT NULL DEFAULT now(),
      CONSTRAINT catalog_products_state_check CHECK (state IN ('draft', 'active', 'archived'))
    )
  `);
  pgm.sql('CREATE INDEX catalog_products_state_idx ON catalog_products (state)');
  pgm.sql('CREATE INDEX catalog_products_slug_idx ON catalog_products (slug)');

  pgm.sql(`
    CREATE TABLE catalog_product_categories (
      product_id uuid NOT NULL REFERENCES catalog_products(id) ON DELETE CASCADE,
      category_id uuid NOT NULL REFERENCES categories_categories(id) ON DELETE RESTRICT,
      created_at timestamptz NOT NULL DEFAULT now(),
      PRIMARY KEY (product_id, category_id)
    )
  `);
  pgm.sql(
    'CREATE INDEX catalog_product_categories_category_id_idx ON catalog_product_categories (category_id)',
  );
};

/** @param {import('node-pg-migrate').MigrationBuilder} pgm */
export const down = (pgm) => {
  pgm.sql('DROP TABLE IF EXISTS catalog_product_categories');
  pgm.sql('DROP TABLE IF EXISTS catalog_products');
};
