<?php

namespace App\Http\Controllers;

use App\Models\Member;
use App\Models\MemberWeekScore;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ScoreController extends Controller
{
    public function indexByWeek(string $week): JsonResponse
    {
        $rows = MemberWeekScore::where('week', $week)->get();

        $byMember = [];
        foreach ($rows as $r) {
            $byMember[(int) $r->member_id] = $r->data;
        }

        return response()->json(['data' => $byMember]);
    }

    public function upsert(Request $request, Member $member, string $week): JsonResponse
    {
        $payload = $request->validate([
            'data' => ['required', 'array'],
        ]);

        $row = MemberWeekScore::updateOrCreate(
            ['member_id' => $member->id, 'week' => $week],
            ['data' => $payload['data']],
        );

        return response()->json([
            'data' => [
                'member_id' => (int) $row->member_id,
                'week' => $row->week,
                'data' => $row->data,
            ],
        ]);
    }
}
