<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Concerns\ScopesApiToAccount;
use App\Models\Drug;
use App\Models\Prescription;
use App\Services\Care\PharmacyService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DrugController extends Controller
{
    use ScopesApiToAccount;

    public function __construct(
        protected PharmacyService $pharmacy,
    ) {}

    public function index(Request $request): JsonResponse
    {
        $this->authorizeAbility($request, 'pharmacy.view');
        $organization = $this->organization($request);

        $drugs = $this->pharmacy->listDrugs(
            $this->ownerRef($request),
            $organization->id,
            $request->only(['q', 'per_page']),
        );

        return response()->json($drugs);
    }

    public function store(Request $request): JsonResponse
    {
        $this->authorizeAbility($request, 'pharmacy.manage');

        $drug = $this->pharmacy->createDrug(
            $this->organization($request),
            $this->ownerRef($request),
            $request->validate([
                'name' => ['required', 'string', 'max:255'],
                'generic_name' => ['nullable', 'string', 'max:255'],
                'sku' => ['nullable', 'string', 'max:100'],
                'unit_price_minor' => ['nullable', 'integer', 'min:0'],
            ]),
        );

        return response()->json($drug, 201);
    }

    public function dispense(Request $request, Prescription $prescription): JsonResponse
    {
        $this->authorizeAbility($request, 'prescriptions.dispense');
        $this->authorizeOwner($request, $prescription);

        $updated = $this->pharmacy->dispensePrescription(
            $prescription,
            $this->ownerRef($request),
            $request->input('allocations', []),
            $this->ownerRef($request),
        );

        return response()->json($updated);
    }
}
