-- name: UpsertRating :one
INSERT INTO ratings (user_id, target_type, target_id, stars, review)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (user_id, target_type, target_id)
DO UPDATE SET stars = EXCLUDED.stars, review = EXCLUDED.review, updated_at = NOW()
RETURNING *;


-- name: GetRatingByUserAndTarget :one
SELECT *
FROM ratings
WHERE user_id = $1 AND target_type = $2 AND target_id = $3;


-- name: GetRatingsByTarget :many
SELECT *
FROM ratings
WHERE target_type = $1 AND target_id = $2
ORDER BY created_at DESC
LIMIT sqlc.narg('limit')::INT
OFFSET sqlc.narg('offset')::INT;


-- name: GetRatingSummary :one
SELECT
    COUNT(*)::BIGINT AS total_count,
    COALESCE(AVG(stars), 0)::FLOAT AS average_stars
FROM ratings
WHERE target_type = $1 AND target_id = $2;


-- name: GetUserRatings :many
SELECT *
FROM ratings
WHERE user_id = $1
ORDER BY updated_at DESC;


-- name: DeleteRating :exec
DELETE FROM ratings
WHERE id = $1 AND user_id = $2;


-- name: CountRatingsByTarget :one
SELECT COUNT(*)::BIGINT
FROM ratings
WHERE target_type = $1 AND target_id = $2;
