/**
 * Brands module table and catalog product-brand assignment.
 */

/** @param {import('node-pg-migrate').MigrationBuilder} pgm */
export const up = (pgm) => {
  pgm.sql(`
    CREATE TABLE brands_brands (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      name text NOT NULL,
      slug text NOT NULL UNIQUE,
      seo_title text,
      seo_description text,
      created_at timestamptz NOT NULL DEFAULT now(),
      updated_at timestamptz NOT NULL DEFAULT now()
    )
  `);
  pgm.sql('CREATE INDEX brands_brands_slug_idx ON brands_brands (slug)');

  pgm.sql(`
    ALTER TABLE catalog_products
      ADD COLUMN brand_id uuid REFERENCES brands_brands(id) ON DELETE SET NULL
  `);
  pgm.sql('CREATE INDEX catalog_products_brand_id_idx ON catalog_products (brand_id)');
};

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