<?php

namespace Controllers;

use Libs\ResponseLib;
use Psr\Http\Message\ServerRequestInterface;
use React\Http\Message\Response;
use Models\CprQueryModel;

class CprQueryController
{
    private CprQueryModel $model;

    public function __construct()
    {
        $this->model = new CprQueryModel();
    }

    public function __invoke(ServerRequestInterface $request)
    {
        $body = json_decode((string)$request->getBody(), true);
        if (!is_array($body)) {
            return ResponseLib::sendFail('Invalid JSON body', [], 'E_VALIDATE')->withStatus(400);
        }

        $authCompanyId = (int)($request->getAttribute('api_company_id') ?? 0);
        if ($authCompanyId <= 0) {
            return ResponseLib::sendFail('Authenticated company not found', [], 'E_VALIDATE')->withStatus(401);
        }

        $hasGlobalAccess = $authCompanyId === 1;
        $cprId = isset($body['cpr_id']) ? (int)$body['cpr_id'] : null;

        try {
            if ($cprId) {
                $record = $hasGlobalAccess
                    ? $this->model->getById($cprId)
                    : $this->model->getByIdAndCompany($cprId, $authCompanyId);
                if (!$record) {
                    return ResponseLib::sendFail(
                        'CPR not found',
                        [],
                        'E_NOT_FOUND'
                    )->withStatus(404);
                }

                return Response::json($record)->withStatus(200);
            }

            $list = $hasGlobalAccess
                ? $this->model->listAll()
                : $this->model->listByCompany($authCompanyId);
            return Response::json($list)->withStatus(200);

        } catch (\Throwable $e) {
            return ResponseLib::sendFail(
                'Failed to query CPRs: ' . $e->getMessage(),
                [],
                'E_DATABASE'
            )->withStatus(500);
        }
    }
}