<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Resources\DestinationResource;
use App\Models\Wisata;
use Database\Seeders\DestinationSeeder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;

class WisataController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $this->seedDefaultDestinationsIfEmpty();

        $wisatas = Wisata::query()
            ->with('kategori')
            ->when($request->kategori_id, fn ($query, string $kategoriId) => $query->where('kategori_id', $kategoriId))
            ->when($request->search, function ($query, string $search): void {
                $query->where(function ($query) use ($search): void {
                    $query->where('title', 'like', "%{$search}%")
                        ->orWhere('location', 'like', "%{$search}%");
                });
            })
            ->latest()
            ->paginate((int) $request->integer('per_page', 10));

        return response()->json([
            'success' => true,
            'message' => 'Success',
            'data' => DestinationResource::collection($wisatas)->response()->getData(true)['data'],
            'meta' => [
                'current_page' => $wisatas->currentPage(),
                'last_page' => $wisatas->lastPage(),
                'per_page' => $wisatas->perPage(),
                'total' => $wisatas->total(),
            ],
        ]);
    }

    public function show(Wisata $wisata): JsonResponse
    {
        $wisata->load('kategori');

        return response()->json([
            'success' => true,
            'message' => 'Success',
            'data' => new DestinationResource($wisata),
        ]);
    }

    public function uploadImage(Request $request, Wisata $wisata): JsonResponse
    {
        $validated = $request->validate([
            'image' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:4096'],
        ]);

        unset($validated);

        if ($wisata->image) {
            Storage::disk('public')->delete($wisata->publicStoragePath($wisata->image));
        }

        $wisata->update([
            'image' => Storage::disk('public')->putFile('wisata', $request->file('image')),
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Success',
            'data' => new DestinationResource($wisata->fresh('kategori')),
        ]);
    }

    private function seedDefaultDestinationsIfEmpty(): void
    {
        if (Wisata::query()->exists()) {
            return;
        }

        Artisan::call('db:seed', [
            '--class' => DestinationSeeder::class,
            '--force' => true,
        ]);
    }
}
