-- name: GetListLocations :many
SELECT * FROM locations;

-- name: GetListRecentLocationsWithRatings :many
SELECT
  l.id,
  name,
  thumbnail,
  COALESCE(re.regency_name, '') as regency_name,
  COALESCE(pr.province_name, '') as province_name,
  (SELECT COALESCE(SUM(score), 0) from reviews re where re.is_from_critic = true and re.location_id = l.id) as critic_score,
  (SELECT COUNT(id) from reviews re where re.is_from_critic = true and re.location_id = l.id) as critic_count,
  (SELECT COALESCE(SUM(score), 0) from reviews re where re.is_from_critic = false and re.location_id = l.id) as user_score,
  (SELECT COUNT(id) from reviews re where re.is_from_critic = false and re.location_id = l.id) as user_count
FROM locations l
JOIN regencies re on re.id = l.regency_id
JOIN provinces pr on re.province_id = pr.id
WHERE approved_by IS NOT NULL
ORDER BY l.created_at ASC
LIMIT $1;

-- name: GetLocationTag :many
SELECT 
  name
FROM tags 
WHERE tags_type = 'location' 
AND 
target_id = $1
AND
approved_by IS NOT NULL;


-- name: UpdateLocationThumbnail :exec
UPDATE locations
SET thumbnail = $1
WHERE id = $2;