<?php

namespace App\Action\Categories;

use App\Domain\Categories\Service\CategoriesService;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

final class CategoriesAction {

    private $CategoriesService;

    public function __construct(CategoriesService $CategoriesService) {
        $this->CategoriesService = $CategoriesService;
    }

    public function __invoke(ServerRequestInterface $request,ResponseInterface $response): ResponseInterface { }

    public function InsertRecord(Request $request,Response $response) {

        //collect input from the HTTP request
        $data = (array)$request->getParsedBody();

        //invoke the Domain with inputs and retain the result
        $result = $this->CategoriesService->InsertarRegistro($data);

        //build the HTTP response | Transform the result into the JSON representation
        $response->getBody()->write(json_encode($result));

        return $response
            ->withHeader('Content-Type', 'application/json')
            ->withStatus(200);
    }

    public function SearchRecords(Request $request,Response $response){

        $payload = $this->CategoriesService->BuscarRegistros();
        $response->getBody()->write(json_encode($payload));

        return $response
            ->withHeader('Content-Type', 'application/json')
            ->withStatus(201);    
    }

    public function SearchRecord(Request $request, Response $response, array $args){

        //id city for get data
        $categoryId = $args['categoryId'];

        $payload=$this->CategoriesService->BuscarRegistro($categoryId);
        $response->getBody()->write(json_encode($payload));

        return $response
            ->withHeader('Content-Type', 'application/json')
            ->withStatus(201);  
    }

    public function UpdateRecord(Request $request,Response $response,array $args){

        // Collect input from the HTTP request
        $data = (array)$request->getParsedBody();

        $result =$this->CategoriesService->ActualizarRegistro($data);     
        $response->getBody()->write(json_encode($result));
        return $response
            ->withHeader('Content-Type', 'application/json')
            ->withStatus(200);   
    }

    public function DeleteRecord(Request $request,Response $response,array $args) {

        $id = $args['categoryId'];

        $result = $this->CategoriesService->EliminarRegistro($id);     
        $response->getBody()->write(json_encode($result));
        
        return $response
            ->withHeader('Content-Type', 'application/json')
            ->withStatus(200);   
    }

}