<?php

namespace App\Http\Controllers;

use App\Models\SpaceBlock;
use App\Services\AuditService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

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

        $blocks = SpaceBlock::query()
            ->with(['space', 'creator'])
            ->when($request->filled('space_id'), fn ($query) => $query->where('space_id', $request->integer('space_id')))
            ->when($request->filled('block_type'), fn ($query) => $query->where('block_type', $request->string('block_type')))
            ->latest('starts_at')
            ->paginate(15)
            ->withQueryString();

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

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

        $space = $spaceBlock->space;
        $oldValues = $spaceBlock->toArray();

        $spaceBlock->delete();

        $auditService->log('space_block.deleted', $spaceBlock, $oldValues);

        return redirect()
            ->route('spaces.show', $space)
            ->with('success', 'Space block removed successfully.');
    }
}
