-- Provider Registry schema (inside rSpace shared DB, schema: providers)
-- Uses earth_distance extension for proximity queries (lighter than PostGIS)

CREATE EXTENSION IF NOT EXISTS "cube";
CREATE EXTENSION IF NOT EXISTS "earthdistance";

CREATE TABLE IF NOT EXISTS providers.providers (
  id              UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  name            VARCHAR(200) NOT NULL,
  description     TEXT,

  -- Location
  lat             DOUBLE PRECISION NOT NULL,
  lng             DOUBLE PRECISION NOT NULL,
  address         TEXT,
  city            VARCHAR(100),
  region          VARCHAR(100),
  country         CHAR(2),
  service_radius_km DOUBLE PRECISION DEFAULT 0,
  offers_shipping BOOLEAN DEFAULT FALSE,

  -- Capabilities & substrates (arrays for containment queries)
  capabilities    TEXT[] NOT NULL DEFAULT '{}',
  substrates      TEXT[] NOT NULL DEFAULT '{}',

  -- Turnaround
  standard_days   INTEGER,
  rush_days       INTEGER,
  rush_surcharge_pct DOUBLE PRECISION DEFAULT 0,

  -- Pricing (JSONB -- keyed by capability)
  pricing         JSONB DEFAULT '{}',

  -- Community membership
  communities     TEXT[] NOT NULL DEFAULT '{}',

  -- Contact
  contact_email   VARCHAR(255),
  contact_phone   VARCHAR(50),
  contact_website VARCHAR(500),

  -- Payment
  wallet          VARCHAR(255),

  -- Reputation
  jobs_completed  INTEGER DEFAULT 0,
  avg_rating      DOUBLE PRECISION,
  member_since    TIMESTAMPTZ DEFAULT NOW(),

  -- Status
  active          BOOLEAN DEFAULT TRUE,

  created_at      TIMESTAMPTZ DEFAULT NOW(),
  updated_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_providers_location
  ON providers.providers USING gist (ll_to_earth(lat, lng));

CREATE INDEX IF NOT EXISTS idx_providers_capabilities
  ON providers.providers USING gin (capabilities);

CREATE INDEX IF NOT EXISTS idx_providers_substrates
  ON providers.providers USING gin (substrates);

CREATE INDEX IF NOT EXISTS idx_providers_communities
  ON providers.providers USING gin (communities);

CREATE INDEX IF NOT EXISTS idx_providers_active
  ON providers.providers (active) WHERE active = TRUE;
