<?php

namespace Modules\Bms\Http\Controllers\Api;

use App\Business;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

/**
 * Base for the BMS REST API. Provides the JSON envelope helpers and resolves
 * the business context for both public (funnel) and authenticated requests.
 */
abstract class ApiController extends Controller
{
    /**
     * Business for public funnel endpoints. Single-tenant by default
     * (config bms.public_business_id, else the first business); an
     * X-Bms-Business header can override it for future multi-brand hosting.
     */
    protected function publicBusinessId(Request $request): int
    {
        $fromHeader = (int) $request->header('X-Bms-Business');
        if ($fromHeader > 0) {
            return $fromHeader;
        }
        $configured = (int) config('bms.public_business_id');
        if ($configured > 0) {
            return $configured;
        }
        return (int) (Business::min('id') ?? 0);
    }

    /** Business for authenticated requests (set by BmsApiAuth). */
    protected function authBusinessId(Request $request): int
    {
        return (int) $request->attributes->get('bms_business_id');
    }

    protected function ok($data = [], int $status = 200)
    {
        return response()->json(['success' => true, 'data' => $data], $status);
    }

    protected function fail(string $message, int $status = 422, array $extra = [])
    {
        return response()->json(array_merge(['success' => false, 'message' => $message], $extra), $status);
    }
}
