package actions

import (
	"fmt"
	"zzman/model"

	"gorm.io/gorm"
)

func FindCities(tx *gorm.DB) ([]model.City, error) {
	var cities []model.City
	if err := tx.Find(&cities, "label is not null").Error; err != nil {
		return nil, fmt.Errorf("failed to find cities: %w", err)
	}
	return cities, nil
}

func FindCitiesWithEdgesCount(tx *gorm.DB) ([]model.City, error) {
	var datas []struct {
		model.City
		EdgesCount int `gorm:"column:edges_count"`
	}
	err := tx.Debug().
		Select("cityhash.*, COUNT(edge.id) AS edges_count").
		Joins("LEFT JOIN edge ON edge.city_id = cityhash.id").
		Where("cityhash.label IS NOT NULL").
		Group("cityhash.id").
		Find(&datas).Error
	if err != nil {
		return nil, fmt.Errorf("failed to find cities with edges count: %w", err)
	}
	var cities = make([]model.City, len(datas))
	for i, data := range datas {
		cities[i] = data.City
		cities[i].EdgesCount = data.EdgesCount
	}
	return cities, nil
}

func AppendCityOffset(tx *gorm.DB, city int, offset int) error {
	if offset < 0 {
		return fmt.Errorf("offset must be non-negative")
	}

	err := tx.Model(&model.City{}).
		Where("id = ?", city).
		Update("offset", offset).Error
	if err != nil {
		return fmt.Errorf("failed to update cities offset: %w", err)
	}

	return nil
}
