CREATE TABLE IF NOT EXISTS loyalty_settings (
  hotel_id         UUID    PRIMARY KEY REFERENCES hotels(id) ON DELETE CASCADE,
  is_active        BOOLEAN NOT NULL DEFAULT true,
  points_per_ruble NUMERIC(10,4) NOT NULL DEFAULT 0.1,
  point_value      NUMERIC(10,4) NOT NULL DEFAULT 0.01,
  expiry_months    INT     NOT NULL DEFAULT 12,
  updated_at       TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS loyalty_transactions (
  id         UUID        PRIMARY KEY DEFAULT gen_random_uuid(),
  hotel_id   UUID        NOT NULL REFERENCES hotels(id) ON DELETE CASCADE,
  guest_id   UUID        NOT NULL REFERENCES guests(id) ON DELETE CASCADE,
  amount     INT         NOT NULL, -- positive = accrual, negative = spend
  reason     VARCHAR(100) NOT NULL DEFAULT 'manual',
  notes      TEXT,
  staff_id   UUID        REFERENCES users(id) ON DELETE SET NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Ensure guests have loyalty columns (may already exist)
ALTER TABLE guests ADD COLUMN IF NOT EXISTS loyalty_tier VARCHAR(20) NOT NULL DEFAULT 'bronze';
ALTER TABLE guests ADD COLUMN IF NOT EXISTS loyalty_points INT NOT NULL DEFAULT 0;
