<?php
namespace Modules\API\APIInterne\Fournisseur\Controller;

use API\Partenaire\IFournissDocExt;
use Entity\Model\Fourniss;
use GuzzleHttp\Psr7\Response;
use Helpers\Fichier\Fichier;
use Helpers\Log\LogSysteme;
use Helpers\Outil\Sql;
use Helpers\Session\ParseBase1;
use Modules\API\APIInterne\Magic\Controller\AbstractController;
use Modules\Fournisseur\Repository\DocAtt;

class FourDocAttController extends AbstractController
{
    /**
     * TODO : factorize with AjaxDocFournisseurController::downloadFichierAction
     * @see \Modules\Fournisseur\Controller\AjaxDocFournisseurController::downloadFichierAction
     * @return Response
     */
    public function getDocAttAction() :Response
    {
        $idFourniss = $this->request->getAttribute('code');
        $numDoc = $this->request->getAttribute('numDoc');

        $docAtt = (new DocAtt($this->pdo))->listForFourniss(
            'FOURNISS',
            $idFourniss,
            ['filter_equal_NO_ORDRE' => $numDoc]
        )[0] ?? null;
        
        if (empty($docAtt['NOM_FIC'])) {
            return $this->createJsonResponse([
                'Error' => 'File not found',
            ], 404);
        }

        if (Sql::toBool($docAtt['GERE_PAR_PARTENAIRE'])) {
            $partn =
                $this->getPartenaireService()
                ->getByCode($docAtt['CodePartenaire']);
            if (! ($partn instanceof IFournissDocExt)) {
                LogSysteme::prefixErrorLog('Invalid partenaire config');
                return $this->createJsonResponse([
                    'Error' => 'PARTN_CONFIG_ERROR',
                ], 500);
            }
            return $partn->downloadDoc($idFourniss, $numDoc);
        }

        $message = Fichier::UploadClient(
            (new ParseBase1())->getRep()->pj . $docAtt['NOM_FIC'],
            $docAtt['NOM_ORI'],
            true
        );
        // Expect Fichier::UploadClient to exit here

        return $this->createJsonResponse([
            'Error' => 'SERVER_ERROR',
            'Message' => $message,
        ], 500);
    }
}
