<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

abstract class ApiController extends Controller
{
    protected function currentUser(Request $request): User
    {
        return $request->user();
    }

    protected function currentCompanyId(Request $request): int
    {
        return (int) ($request->attributes->get('company_id') ?? $this->currentUser($request)->company_id);
    }

    protected function currentBranchId(Request $request): ?int
    {
        $branchId = $request->attributes->get('branch_id');

        return $branchId === null ? null : (int) $branchId;
    }

    protected function ensureCompanyScoped(Model $model, int $companyId, string $column = 'company_id'): void
    {
        if ((int) $model->getAttribute($column) !== $companyId) {
            abort(404);
        }
    }

    protected function ensureBranchScoped(Model $model, int $branchId, string $column = 'branch_id'): void
    {
        if ((int) $model->getAttribute($column) !== $branchId) {
            abort(404);
        }
    }

    protected function validationError(string $key, string $message): never
    {
        throw ValidationException::withMessages([$key => [$message]]);
    }
}
