-- +goose Up

ALTER TABLE assignment_assignees
    ADD COLUMN ai_feedback TEXT,
    ADD COLUMN teacher_feedback TEXT;

UPDATE assignment_assignees aa
SET ai_feedback = aggregated.ai_feedback
FROM (
    SELECT
        sa.assignment_id,
        sa.student_id,
        string_agg(
            format('Question %s: %s', aq.position, btrim(sa.ai_feedback)),
            E'\n\n'
            ORDER BY aq.position ASC
        ) AS ai_feedback
    FROM student_answers sa
    JOIN assignment_questions aq
        ON aq.assignment_id = sa.assignment_id
       AND aq.question_id = sa.question_id
    WHERE NULLIF(btrim(sa.ai_feedback), '') IS NOT NULL
    GROUP BY sa.assignment_id, sa.student_id
) AS aggregated
WHERE aa.assignment_id = aggregated.assignment_id
  AND aa.student_id = aggregated.student_id;

UPDATE assignment_assignees aa
SET teacher_feedback = aggregated.teacher_feedback
FROM (
    SELECT
        sa.assignment_id,
        sa.student_id,
        string_agg(
            format('Question %s: %s', aq.position, btrim(sa.teacher_feedback)),
            E'\n\n'
            ORDER BY aq.position ASC
        ) AS teacher_feedback
    FROM student_answers sa
    JOIN assignment_questions aq
        ON aq.assignment_id = sa.assignment_id
       AND aq.question_id = sa.question_id
    WHERE NULLIF(btrim(sa.teacher_feedback), '') IS NOT NULL
    GROUP BY sa.assignment_id, sa.student_id
) AS aggregated
WHERE aa.assignment_id = aggregated.assignment_id
  AND aa.student_id = aggregated.student_id;

-- +goose Down

ALTER TABLE assignment_assignees
    DROP COLUMN IF EXISTS teacher_feedback,
    DROP COLUMN IF EXISTS ai_feedback;
