<?php

namespace App\Http\Controllers\Api\V1\Coach;

use App\Http\Controllers\Controller;
use App\Http\Resources\Api\CoachSessionResource;
use App\Models\Coach;
use App\Services\CoachScheduleService;
use App\Traits\ApiResponseTrait;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ScheduleController extends Controller
{
    use ApiResponseTrait;

    public function __construct(
        protected CoachScheduleService $scheduleService
    ) {}

    /**
     * GET /coach/schedule?date=YYYY-MM-DD
     * My Schedule screen: daily sessions list + stats.
     */
    public function index(Request $request): JsonResponse
    {
        $coach = $request->user();

        if (! $coach instanceof Coach) {
            return $this->errorResponse(__('Unauthorized.'), 403);
        }

        $date = $request->input('date', now()->toDateString());

        $sessions = $this->scheduleService->getSessionsForDate($coach, $date);
        $stats    = $this->scheduleService->getDateStats($coach, $date);

        return $this->ApiResponse([
            'date'     => $date,
            'stats'    => $stats,
            'sessions' => CoachSessionResource::collection($sessions),
        ], __('Success'), 200);
    }

    /**
     * GET /coach/schedule/{id}
     * Session detail with attendance list.
     */
    public function show(Request $request, int $id): JsonResponse
    {
        $coach = $request->user();

        if (! $coach instanceof Coach) {
            return $this->errorResponse(__('Unauthorized.'), 403);
        }

        $session = $this->scheduleService->getSessionDetail($id, $coach);

        if (! $session) {
            return $this->notFoundResponse();
        }

        return $this->ApiResponse(
            (new CoachSessionResource($session))->forShow(),
            __('Success'),
            200
        );
    }
}
