-- Add services table and link offices to services

-- 1) Create services table
CREATE TABLE IF NOT EXISTS services (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  name text NOT NULL UNIQUE
);

-- 2) Add service_id to offices
ALTER TABLE IF EXISTS offices
  ADD COLUMN IF NOT EXISTS service_id uuid REFERENCES services(id) ON DELETE SET NULL;

-- 3) Insert default services
INSERT INTO services (name) VALUES
  ('Medical Center Chief'),
  ('Medical Service'),
  ('Nursing Service'),
  ('Hospital Operations and Patient Support Service'),
  ('Finance Service'),
  ('Allied/Ancillary')
ON CONFLICT (name) DO NOTHING;

-- 4) Make existing offices default to Medical Center Chief (for now)
UPDATE offices
SET service_id = s.id
FROM services s
WHERE s.name = 'Medical Center Chief';

-- 5) (Optional) Add index for faster lookups
CREATE INDEX IF NOT EXISTS idx_offices_service_id ON offices(service_id);
