<?php

namespace App\Modules\FactReceiptDetail\Infraestructure;

use App\Modules\FactProduct\Domain\FactProduct;
use App\Modules\FactReceiptDetail\Domain\FactReceiptDetail;
use App\Modules\FactReceiptDetail\Domain\FactReceiptDetailRepository;
use App\Modules\FactReceiptDetail\Domain\IdFactReceiptDetail;
use App\Modules\FactReceiptDetail\Domain\UpdateFactReceiptDetail;
use App\Modules\FactUnit\Domain\FactUnit;
use App\Modules\Shared\Domain\Storage\Criteria\StorageCriteria;
use App\Modules\Shared\Infraestructure\Requester;

class MysqlFactReceiptDetailRepository implements FactReceiptDetailRepository
{

    public function find(StorageCriteria $criteria): FactReceiptDetail
    {
        $dto = $criteria->run();
        $factReceiptDetail = FactReceiptDetail::fromDTO($dto);
        $factReceiptDetail->setProduct(FactProduct::fromDTO($dto));
        return $factReceiptDetail;
    }

    public function search(StorageCriteria $criteria): array
    {
        return array_map(function ($dto) {
            $factReceiptDetail = FactReceiptDetail::fromDTO($dto);
            $factReceiptDetail->setProduct(FactProduct::fromDTO($dto));
            $factReceiptDetail->setUnit(FactUnit::fromDTO($dto));
            return $factReceiptDetail;
        }, $criteria->run());
    }

    public function insert(FactReceiptDetail $value)
    {
        return Requester::requestInsert(
            'CALL sp_fact_receipt_detail_insert(?,?,?,?,?,?,?,?,?,@sts,@cod,@msg,@id)',
            [
                $value->amount()->value(),
                $value->unitPrice()->value(),
                $value->discount()->value(),
                $value->total()->value(),
                $value->status()->value(),
                $value->idFactProduct()->value(),
                $value->idFactTypeOperation()->value(),
                $value->idFactUnit()->value(),
                $value->idFactReceipt()->value(),
            ]
        );
    }

    public function update(UpdateFactReceiptDetail $value)
    {
        return Requester::requestUpdate(
            'CALL sp_fact_receipt_detail_update(?,?,?,?,?,?,?,?,?,?,@sts,@cod,@msg)',
            [
                $value->id()->value(),
                $value->amount()->value(),
                $value->unitPrice()->value(),
                $value->discount()->value(),
                $value->total()->value(),
                $value->idFactTypeOperation()->value(),
                $value->idFactUnit()->value(),
                $value->factProductCode()->value(),
                $value->factProductName()->value(),
                $value->factProductIdProduct()->value(),
            ]
        );
    }

    public function delete(IdFactReceiptDetail $id)
    {
        return Requester::requestUpdate(
            'CALL sp_fact_receipt_detail_delete(?,@sts,@cod,@msg)',
            [
                $id->value(),
            ]
        );
    }
}
