<?php

namespace App\Services\Client;

use App\Models\CoachLocation;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;

class CoachLocationService
{
    /**
     * 获取技师定位地址列表
     */
    public function getAllLocations()
    {
        // 从 Redis 中获取所有技师定位地址
        $locationNames = Redis::zrange('coach_locations', 0, -1);

        $result = [];
        foreach ($locationNames as $locationName) {
            $positions = Redis::geopos('coach_locations', $locationName);
            if (! empty($positions) && isset($positions[0])) {
                [$longitude, $latitude] = $positions[0];
                [$coachId, $type] = explode('_', $locationName);
                $result[] = [
                    'coach_id' => $coachId,
                    'type' => $type,
                    'longitude' => $longitude,
                    'latitude' => $latitude,
                ];
            }
        }

        return response()->json($result);
        // return CoachLocation::all();
    }

    /**
     * 创建技师定位地址
     */
    public function createLocation(array $data)
    {
        $user = Auth::user();
        $coach = $user->coach;
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $type = $data['type'];
        $locationName = $coach->id.'_'.$type; // 假设数据中有一个名称字段

        // 使用 Redis 的 GEOADD 命令
        Redis::geoadd('coach_locations', $longitude, $latitude, $locationName);
        $location = $coach->locations()->where('type', $type)->first();
        if ($location) {
            $location->update($data);
        } else {
            $coach->locations()->create($data);
        }

        return response()->json(['message' => 'Location added successfully']);
    }

    /**
     * 删除技师定位地址
     */
    public function deleteLocation($coachId, $type)
    {
        $location = CoachLocation::where('type', $type)
            ->where('coach_id', $coachId)
            ->first();
        $location?->delete();

        // 从 Redis 中删除地理位置记录
        $locationName = $coachId.'_'.$type;
        Redis::zrem('coach_locations', $locationName);

        return response()->json(['message' => 'Deleted successfully']);
    }
}
