<?php

namespace App\Http\Controllers;

use App\Models\Album;
use App\Models\Track;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AlbumController extends Controller
{
    public function index(): JsonResponse
    {
        return response()->json(Album::with(['label', 'artist', 'genres', 'tracks.artists', 'tracks.genres'])->get());
    }

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

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'title'            => 'required|string|max:255',
            'cover_path'       => 'nullable|string|max:255',
            'release_date'     => 'nullable|date',
            'duration_seconds' => 'nullable|integer',
            'type'             => 'nullable|in:album,single,ep',
            'label_id'         => 'nullable|exists:labels,id',
            'artist_id'        => 'nullable|exists:artists,id',
            'genre_ids'        => 'nullable|array',
            'genre_ids.*'      => 'exists:genres,id',
        ]);

        $genreIds = $data['genre_ids'] ?? [];
        unset($data['genre_ids']);

        $album = Album::create($data);

        if (!empty($genreIds)) {
            $album->genres()->sync($genreIds);
        }

        if ($request->has('tracks')) {
            foreach ($request->input('tracks') as $index => $trackData) {
                $album->tracks()->create([
                    'title'    => $trackData['title'],
                    'file_path' => $trackData['file_path'] ?? '',
                    'position' => $trackData['position'] ?? $index,
                ]);
            }
        }

        return response()->json($album->load(['label', 'artist', 'genres', 'tracks.artists', 'tracks.genres']), 201);
    }

    public function update(Request $request, Album $album): JsonResponse
    {
        $data = $request->validate([
            'title'            => 'sometimes|required|string|max:255',
            'cover_path'       => 'nullable|string|max:255',
            'release_date'     => 'nullable|date',
            'duration_seconds' => 'nullable|integer',
            'type'             => 'nullable|in:album,single,ep',
            'label_id'         => 'nullable|exists:labels,id',
            'artist_id'        => 'nullable|exists:artists,id',
            'genre_ids'        => 'nullable|array',
            'genre_ids.*'      => 'exists:genres,id',
        ]);

        $genreIds = $data['genre_ids'] ?? null;
        unset($data['genre_ids']);

        $album->update($data);

        if ($genreIds !== null) {
            $album->genres()->sync($genreIds);
        }

        return response()->json($album->load(['label', 'artist', 'genres', 'tracks.artists', 'tracks.genres']));
    }

    public function destroy(Album $album): JsonResponse
    {
        $album->delete();

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