<?php

namespace App\Http\Controllers;

use App\Models\Artist;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ArtistController extends Controller
{
    public function index(): JsonResponse
    {
        return response()->json(Artist::with('label')->get());
    }

    public function show(Artist $artist): JsonResponse
    {
        return response()->json($artist->load(['label', 'tracks.album', 'tracks.genres']));
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name'         => 'required|string|max:255',
            'cover_path'   => 'nullable|string|max:255',
            'release_date' => 'nullable|date',
            'label_id'     => 'nullable|exists:labels,id',
            'duration'     => 'nullable|integer',
        ]);

        $artist = Artist::create($data);

        return response()->json($artist->load('label'), 201);
    }

    public function update(Request $request, Artist $artist): JsonResponse
    {
        $data = $request->validate([
            'name'         => 'sometimes|required|string|max:255',
            'cover_path'   => 'nullable|string|max:255',
            'release_date' => 'nullable|date',
            'label_id'     => 'nullable|exists:labels,id',
            'duration'     => 'nullable|integer',
        ]);

        $artist->update($data);

        return response()->json($artist->load('label'));
    }

    public function destroy(Artist $artist): JsonResponse
    {
        $artist->delete();

        return response()->json(null, 204);
    }
}
