-- Ensure office management works for the new `programmer` role.
--
-- If RLS is enabled for offices, insert/update/delete operations can fail unless
-- there is an explicit policy allowing those roles.

ALTER TABLE IF EXISTS offices ENABLE ROW LEVEL SECURITY;

-- Allow any authenticated user to read offices (used for dropdowns/filters).
DROP POLICY IF EXISTS "Offices: select auth" ON offices;
CREATE POLICY "Offices: select auth" ON offices
  FOR SELECT
  USING (auth.role() IS NOT NULL);

-- Allow admin/dispatcher/programmer to insert/update/delete offices.
DROP POLICY IF EXISTS "Offices: manage" ON offices;
CREATE POLICY "Offices: manage" ON offices
  FOR ALL
  USING (
    EXISTS (
      SELECT 1 FROM profiles p
      WHERE p.id = auth.uid()
        AND p.role IN ('admin', 'dispatcher', 'programmer')
    )
  )
  WITH CHECK (
    EXISTS (
      SELECT 1 FROM profiles p
      WHERE p.id = auth.uid()
        AND p.role IN ('admin', 'dispatcher', 'programmer')
    )
  );
