<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Service;
use App\Support\PublicUploader;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\View\View;

class ServiceController extends Controller
{
    public function index(): View
    {
        return view('tenant.services.index');
    }

    public function create(): View
    {
        return view('tenant.services.create');
    }

    public function edit(Service $service): View
    {
        $this->authorize('update', $service);
        return view('tenant.services.edit', compact('service'));
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $this->validatedData($request);
        unset($data['image'], $data['remove_image']);
        $data['slug'] = $this->uniqueSlug($data['name']);
        $data['is_active'] = $request->boolean('is_active');
        $data['is_public'] = $request->boolean('is_public');
        $data['is_home_service'] = $request->boolean('is_home_service');

        if ($request->hasFile('image')) {
            $data['image_path'] = PublicUploader::store($request->file('image'), 'services');
        }

        Service::create($data);

        return redirect()->route('tenant.services.index')
            ->with('success', 'Servicio creado correctamente.');
    }

    public function update(Request $request, Service $service): RedirectResponse
    {
        $this->authorize('update', $service);

        $data = $this->validatedData($request);
        unset($data['image'], $data['remove_image']);
        $data['is_active'] = $request->boolean('is_active');
        $data['is_public'] = $request->boolean('is_public');
        $data['is_home_service'] = $request->boolean('is_home_service');

        if ($request->boolean('remove_image') && $service->image_path) {
            PublicUploader::delete($service->image_path);
            $data['image_path'] = null;
        }

        if ($request->hasFile('image')) {
            if ($service->image_path) {
                PublicUploader::delete($service->image_path);
            }

            $data['image_path'] = PublicUploader::store($request->file('image'), 'services');
        }

        $service->update($data);

        return redirect()->route('tenant.services.index')
            ->with('success', 'Servicio actualizado correctamente.');
    }

    public function destroy(Service $service): RedirectResponse
    {
        $this->authorize('delete', $service);
        if ($service->image_path) {
            PublicUploader::delete($service->image_path);
        }

        $service->delete();

        return redirect()->route('tenant.services.index')
            ->with('success', 'Servicio eliminado correctamente.');
    }

    protected function validatedData(Request $request): array
    {
        return $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:2000'],
            'service_category_id' => ['nullable', 'exists:service_categories,id'],
            'price' => ['required', 'numeric', 'min:0'],
            'duration_minutes' => ['required', 'integer', 'min:5'],
            'buffer_minutes' => ['nullable', 'integer', 'min:0'],
            'cancellation_min_notice_minutes' => ['nullable', 'integer', 'min:0', 'max:10080'],
            'image' => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:4096'],
            'remove_image' => ['nullable', 'boolean'],
        ]);
    }

    protected function uniqueSlug(string $name): string
    {
        $base = Str::slug($name) ?: 'servicio';
        $slug = $base;
        $counter = 2;

        while (Service::where('slug', $slug)->exists()) {
            $slug = "{$base}-{$counter}";
            $counter++;
        }

        return $slug;
    }
}
