<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Branch\StoreBranchRequest;
use App\Http\Requests\Branch\UpdateBranchRequest;
use App\Http\Resources\BranchResource;
use App\Models\Branch;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class BranchController extends ApiController
{
    public function index(Request $request): AnonymousResourceCollection
    {
        $branches = Branch::query()
            ->where('company_id', $this->currentCompanyId($request))
            ->get();

        return BranchResource::collection($branches);
    }

    public function store(StoreBranchRequest $request): BranchResource
    {
        $branch = Branch::create([
            ...$request->validated(),
            'company_id' => $this->currentCompanyId($request),
        ]);

        return new BranchResource($branch);
    }

    public function show(Request $request, Branch $branch): BranchResource
    {
        $this->ensureCompanyScoped($branch, $this->currentCompanyId($request));

        return new BranchResource($branch);
    }

    public function update(UpdateBranchRequest $request, Branch $branch): BranchResource
    {
        $this->ensureCompanyScoped($branch, $this->currentCompanyId($request));
        $branch->update($request->validated());

        return new BranchResource($branch);
    }

    public function destroy(Request $request, Branch $branch): \Illuminate\Http\JsonResponse
    {
        $this->ensureCompanyScoped($branch, $this->currentCompanyId($request));

        if ($branch->shifts()->exists()) {
            return response()->json([
                'message' => 'Branch cannot be deleted while it has shift history.'
            ], 422);
        }

        $branch->delete();

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