<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreSpaceTypeRequest;
use App\Http\Requests\UpdateSpaceTypeRequest;
use App\Models\SpaceType;
use App\Services\AuditService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SpaceTypeController extends Controller
{
    public function index(Request $request): View
    {
        $this->authorize('viewAny', SpaceType::class);

        $spaceTypes = SpaceType::query()
            ->when($request->filled('search'), fn ($query) => $query->where('name', 'like', '%'.$request->string('search').'%'))
            ->orderBy('sort_order')
            ->orderBy('name')
            ->paginate(15)
            ->withQueryString();

        return view('space-types.index', compact('spaceTypes'));
    }

    public function create(): View
    {
        $this->authorize('create', SpaceType::class);

        return view('space-types.create');
    }

    public function store(StoreSpaceTypeRequest $request, AuditService $auditService): RedirectResponse
    {
        $this->authorize('create', SpaceType::class);

        $spaceType = SpaceType::query()->create($request->validated());

        $auditService->log('space_type.created', $spaceType, null, $spaceType->toArray());

        return redirect()
            ->route('space-types.index')
            ->with('success', 'Space type created successfully.');
    }

    public function edit(SpaceType $spaceType): View
    {
        $this->authorize('update', $spaceType);

        return view('space-types.edit', compact('spaceType'));
    }

    public function update(UpdateSpaceTypeRequest $request, SpaceType $spaceType, AuditService $auditService): RedirectResponse
    {
        $this->authorize('update', $spaceType);

        $oldValues = $spaceType->toArray();
        $spaceType->update($request->validated());

        $auditService->log('space_type.updated', $spaceType, $oldValues, $spaceType->fresh()->toArray());

        return redirect()
            ->route('space-types.index')
            ->with('success', 'Space type updated successfully.');
    }

    public function destroy(SpaceType $spaceType, AuditService $auditService): RedirectResponse
    {
        $this->authorize('delete', $spaceType);

        if ($spaceType->spaces()->exists()) {
            return back()->with('error', 'Cannot delete a space type that has spaces assigned.');
        }

        $oldValues = $spaceType->toArray();
        $spaceType->delete();

        $auditService->log('space_type.deleted', $spaceType, $oldValues);

        return redirect()
            ->route('space-types.index')
            ->with('success', 'Space type deleted successfully.');
    }
}
