<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\ListingType;
use App\Services\ImageService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class ListingTypeController extends Controller
{
    public function index(): JsonResponse
    {
        $types = ListingType::withCount('listings')
            ->orderBy('name')
            ->get();

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

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'slug' => ['nullable', 'string', 'max:255', 'unique:listing_types,slug'],
            'description' => ['nullable', 'string'],
            'icon' => ['nullable', 'string', 'max:50'],
            'image' => ['nullable', 'image', 'max:2048'],
            'is_active' => ['boolean'],
        ]);

        $slug = $validated['slug'] ?? Str::slug($validated['name']);

        $imagePath = null;
        if ($request->hasFile('image')) {
            $imageService = app(ImageService::class);
            $imagePath = $imageService->compress(
                $request->file('image'),
                'listing-types',
                ImageService::PRESET_CATEGORY,
            );
        }

        $type = ListingType::create([
            'name' => $validated['name'],
            'slug' => $slug,
            'description' => $validated['description'] ?? null,
            'icon' => $validated['icon'] ?? null,
            'image' => $imagePath,
            'is_active' => $validated['is_active'] ?? true,
        ]);

        $type->loadCount('listings');

        return response()->json(['type' => $type], 201);
    }

    public function show(ListingType $listingType): JsonResponse
    {
        $listingType->loadCount('listings');

        return response()->json(['type' => $listingType]);
    }

    public function update(Request $request, ListingType $listingType): JsonResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'slug' => ['nullable', 'string', 'max:255', Rule::unique('listing_types', 'slug')->ignore($listingType->id)],
            'description' => ['nullable', 'string'],
            'icon' => ['nullable', 'string', 'max:50'],
            'image' => ['nullable', 'image', 'max:2048'],
            'is_active' => ['boolean'],
        ]);

        if ($request->hasFile('image')) {
            if ($listingType->image) {
                Storage::disk('public')->delete($listingType->image);
            }
            $imageService = app(ImageService::class);
            $validated['image'] = $imageService->compress(
                $request->file('image'),
                'listing-types',
                ImageService::PRESET_CATEGORY,
            );
        }

        if (!isset($validated['slug']) || !$validated['slug']) {
            $validated['slug'] = Str::slug($validated['name']);
        }

        $listingType->update($validated);
        $listingType->loadCount('listings');

        return response()->json(['type' => $listingType]);
    }

    public function destroy(ListingType $listingType): JsonResponse
    {
        if ($listingType->listings()->exists()) {
            return response()->json([
                'message' => 'Bu kategoriye ait ilanlar bulunduğu için silinemez.',
            ], 422);
        }

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

        $listingType->delete();

        return response()->json(['message' => 'Kategori başarıyla silindi.']);
    }

    public function removeImage(ListingType $listingType): JsonResponse
    {
        if ($listingType->image) {
            Storage::disk('public')->delete($listingType->image);
            $listingType->update(['image' => null]);
        }

        $listingType->loadCount('listings');

        return response()->json(['type' => $listingType]);
    }
}
