-- Pass slip system for duty excusals
CREATE TABLE IF NOT EXISTS pass_slips (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL REFERENCES auth.users(id),
  duty_schedule_id uuid NOT NULL REFERENCES duty_schedules(id),
  reason text NOT NULL,
  status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected', 'completed')),
  requested_at timestamptz NOT NULL DEFAULT now(),
  approved_by uuid REFERENCES auth.users(id),
  approved_at timestamptz,
  slip_start timestamptz,
  slip_end timestamptz
);

CREATE INDEX idx_pass_slips_user ON pass_slips (user_id, requested_at DESC);
CREATE INDEX idx_pass_slips_status ON pass_slips (status) WHERE status IN ('pending', 'approved');

-- Enable realtime
ALTER PUBLICATION supabase_realtime ADD TABLE pass_slips;

-- RLS
ALTER TABLE pass_slips ENABLE ROW LEVEL SECURITY;

-- Users can see their own pass slips; admin/dispatcher can see all
CREATE POLICY "pass_slips_select" ON pass_slips FOR SELECT TO authenticated
USING (
  user_id = auth.uid()
  OR EXISTS (
    SELECT 1 FROM profiles p WHERE p.id = auth.uid() AND p.role IN ('admin', 'dispatcher')
  )
);

-- Users can insert their own pass slips
CREATE POLICY "pass_slips_insert" ON pass_slips FOR INSERT TO authenticated
WITH CHECK (user_id = auth.uid());

-- Admins can update pass slips (approve/reject); users can complete their own
CREATE POLICY "pass_slips_update" ON pass_slips FOR UPDATE TO authenticated
USING (
  user_id = auth.uid()
  OR EXISTS (
    SELECT 1 FROM profiles p WHERE p.id = auth.uid() AND p.role IN ('admin', 'dispatcher')
  )
);
