CREATE OR REPLACE VIEW engineer_ratings_view AS
SELECT
  s.engineer_name,
  s.id_user,
  COUNT(DISTINCT s.id) AS total_surveys,
  ROUND(AVG( (jt.answer / jt.levels) * 5 ), 2) AS average_rating
FROM surveys_answers s
JOIN JSON_TABLE(
  s.snapshot_json,
  '$[*]' COLUMNS (
    answer DECIMAL(5,2) PATH '$.answer',
    levels DECIMAL(5,2) PATH '$.levels'
  )
) jt ON s.snapshot_json IS NOT NULL
WHERE s.id_user IS NOT NULL
GROUP BY s.id_user, s.engineer_name;
