<?php

namespace Modules\LotesSeries\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Modules\LotesSeries\Services\RastreabilidadeService;

class RastreabilidadeController {
    public function rastrearLote(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $loteId = (int)($req->get('params')[0] ?? 0);

            $service = new RastreabilidadeService($tenantId);
            $rastreabilidade = $service->rastrearLote($loteId);

            return Response::json(['data' => $rastreabilidade]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function rastrearSerie(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $serieId = (int)($req->get('params')[0] ?? 0);

            $service = new RastreabilidadeService($tenantId);
            $rastreabilidade = $service->rastrearSerie($serieId);

            return Response::json(['data' => $rastreabilidade]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function rastrearProduto(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $productId = (int)($req->get('params')[0] ?? 0);

            $service = new RastreabilidadeService($tenantId);
            $rastreabilidade = $service->rastrearProduto($productId);

            return Response::json(['data' => $rastreabilidade]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function criarRecall(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $body = is_array($req->body) ? $req->body : [];

            $service = new RastreabilidadeService($tenantId);
            $recallId = $service->criarRecall($body);

            return Response::json(['data' => ['id' => $recallId]], 201);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }
}

