-- Enable RLS on task_activity_logs and allow authenticated inserts
-- Also add cancelled_at column to tasks table if missing

-- Enable RLS for task_activity_logs (idempotent)
DO $$
BEGIN
  IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name='task_activity_logs') THEN
    EXECUTE 'ALTER TABLE public.task_activity_logs ENABLE ROW LEVEL SECURITY';
  END IF;
EXCEPTION WHEN others THEN
  -- ignore
END
$$;

-- Create a permissive INSERT policy for authenticated users (idempotent)
DO $$
BEGIN
  IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name='task_activity_logs') THEN
    IF NOT EXISTS (
      SELECT 1 FROM pg_policies WHERE polname = 'allow_authenticated_inserts'
        AND polrelid = 'public.task_activity_logs'::regclass
    ) THEN
      CREATE POLICY allow_authenticated_inserts
        ON public.task_activity_logs
        FOR INSERT
        TO authenticated
        USING (true)
        WITH CHECK (true);
    END IF;
  END IF;
EXCEPTION WHEN others THEN
  -- ignore
END
$$;

-- Add cancelled_at column to tasks if it does not exist
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_name='tasks' AND column_name='cancelled_at'
  ) THEN
    ALTER TABLE public.tasks ADD COLUMN cancelled_at timestamptz;
  END IF;
END
$$;
