<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\DiningTable\StoreTableRequest;
use App\Http\Requests\DiningTable\UpdateTableRequest;
use App\Http\Resources\DiningTableResource;
use App\Models\DiningTable;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class DiningTableController extends ApiController
{
    public function index(Request $request): AnonymousResourceCollection
    {
        $branchId = $this->currentBranchId($request);
        if (!$branchId) {
            abort(400, 'Branch context is required for dining tables.');
        }

        $tables = DiningTable::query()
            ->where('branch_id', $branchId)
            ->orderBy('name')
            ->get();

        return DiningTableResource::collection($tables);
    }

    public function store(StoreTableRequest $request): DiningTableResource
    {
        $branchId = $this->currentBranchId($request);
        
        $table = DiningTable::create([
            ...$request->validated(),
            'branch_id' => $branchId,
            'status' => 'available',
        ]);

        return new DiningTableResource($table);
    }

    public function show(Request $request, DiningTable $diningTable): DiningTableResource
    {
        $this->ensureBranchScoped($diningTable, $this->currentBranchId($request));
        
        return new DiningTableResource($diningTable);
    }

    public function update(UpdateTableRequest $request, DiningTable $diningTable): DiningTableResource
    {
        $this->ensureBranchScoped($diningTable, $this->currentBranchId($request));
        $diningTable->update($request->validated());

        return new DiningTableResource($diningTable);
    }

    public function destroy(Request $request, DiningTable $diningTable): \Illuminate\Http\JsonResponse
    {
        $this->ensureBranchScoped($diningTable, $this->currentBranchId($request));
        
        $diningTable->delete();

        return response()->json(['message' => 'Dining table deleted successfully']);
    }
}
