/**
 * F-186 — Configurable POS receipts and free sale lines.
 *
 * @param {import('node-pg-migrate').MigrationBuilder} pgm
 */

const DEFAULT_STORE_ID = '00000000-0000-0000-0000-000000000001';

export const up = (pgm) => {
  pgm.sql(`
    CREATE TABLE IF NOT EXISTS pos_receipt_settings (
      store_id uuid PRIMARY KEY REFERENCES pos_stores(id) ON DELETE CASCADE,
      prefix text NOT NULL DEFAULT 'TPV',
      next_number bigint NOT NULL DEFAULT 1,
      padding integer NOT NULL DEFAULT 6,
      return_policy text NOT NULL DEFAULT 'Se admiten devoluciones durante 15 días con el ticket de compra.',
      updated_at timestamptz NOT NULL DEFAULT now(),
      CONSTRAINT pos_receipt_settings_next_positive CHECK (next_number > 0),
      CONSTRAINT pos_receipt_settings_padding_check CHECK (padding BETWEEN 1 AND 12),
      CONSTRAINT pos_receipt_settings_prefix_check CHECK (prefix ~ '^[A-Za-z0-9_-]{1,16}$')
    )
  `);

  pgm.sql(`
    INSERT INTO pos_receipt_settings (store_id)
    VALUES ('${DEFAULT_STORE_ID}')
    ON CONFLICT (store_id) DO NOTHING
  `);

  pgm.sql('ALTER TABLE orders_orders ADD COLUMN IF NOT EXISTS receipt_number text');
  pgm.sql(`
    CREATE UNIQUE INDEX IF NOT EXISTS orders_orders_receipt_number_unique_idx
      ON orders_orders (store_id, receipt_number)
      WHERE receipt_number IS NOT NULL
  `);

  pgm.sql('ALTER TABLE orders_items ALTER COLUMN product_id DROP NOT NULL');
  pgm.sql('ALTER TABLE orders_items ALTER COLUMN variant_id DROP NOT NULL');
  pgm.sql(
    'ALTER TABLE orders_items ADD COLUMN IF NOT EXISTS is_free_item boolean NOT NULL DEFAULT false',
  );
  pgm.sql(`
    DO $$
    BEGIN
      IF NOT EXISTS (
        SELECT 1 FROM pg_constraint WHERE conname = 'orders_items_stock_or_free_check'
      ) THEN
        ALTER TABLE orders_items
          ADD CONSTRAINT orders_items_stock_or_free_check
          CHECK (
            (is_free_item AND product_id IS NULL AND variant_id IS NULL)
            OR
            (NOT is_free_item AND product_id IS NOT NULL AND variant_id IS NOT NULL)
          );
      END IF;
    END $$
  `);
};

export const down = (pgm) => {
  pgm.sql('ALTER TABLE orders_items DROP CONSTRAINT IF EXISTS orders_items_stock_or_free_check');
  pgm.sql('ALTER TABLE orders_items DROP COLUMN IF EXISTS is_free_item');
  pgm.sql('ALTER TABLE orders_items ALTER COLUMN variant_id SET NOT NULL');
  pgm.sql('ALTER TABLE orders_items ALTER COLUMN product_id SET NOT NULL');
  pgm.sql('DROP INDEX IF EXISTS orders_orders_receipt_number_unique_idx');
  pgm.sql('ALTER TABLE orders_orders DROP COLUMN IF EXISTS receipt_number');
  pgm.dropTable('pos_receipt_settings', { ifExists: true });
};
