CREATE OR REPLACE FUNCTION update_days_read () RETURNS TRIGGER AS $$
DECLARE
  pacific_today DATE;
  last_read DATE;
BEGIN
  SELECT (NOW() AT TIME ZONE 'America/Los_Angeles')::DATE INTO pacific_today;
  SELECT COALESCE(last_read_date::DATE, pacific_today - INTERVAL '1 day') INTO last_read
  FROM reading_streak
  LIMIT 1;
  IF last_read < pacific_today - INTERVAL '1 day' THEN
    UPDATE reading_streak
    SET days_read = 1, last_read_date = pacific_today
    WHERE id = 1;
  ELSIF last_read < pacific_today THEN
    UPDATE reading_streak
    SET days_read = days_read + 1, last_read_date = pacific_today
    WHERE id = 1;
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;
