<?php

namespace WMS\Controllers;

use WMS\Core\Request;
use WMS\Core\Response;
use WMS\Middleware\AuthMiddleware;
use WMS\Services\PutawayService;
use WMS\Helpers\Validator;

class PutawayController
{
    /**
     * POST /api/putaway/grouped
     * Putaway de toda una etiqueta de transferencia a un solo bin.
     * Body: { label_id, to_bin_id }
     */
    public static function grouped(array $params): void
    {
        $body = Request::body();
        $v = (new Validator($body))->required(['label_id', 'to_bin_id']);

        if (!$v->passes()) {
            Response::error('Datos inválidos', 422, $v->errors());
            return;
        }

        try {
            $service = new PutawayService();
            $result = $service->groupedPutaway(
                (int) $body['label_id'],
                (int) $body['to_bin_id'],
                AuthMiddleware::userId()
            );
            Response::success($result, 'Putaway agrupado completado');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage());
        }
    }

    /**
     * GET /api/putaway/suggest/{item_id}?warehouse_id=
     * Sugiere el mejor bin para guardar un artículo.
     */
    public static function suggest(array $params): void
    {
        $warehouseId = Request::query('warehouse_id');
        if (!$warehouseId) {
            Response::error('warehouse_id es requerido', 422);
            return;
        }

        try {
            $service = new PutawayService();
            $result = $service->suggestBin(
                (int) $params['item_id'],
                (int) $warehouseId
            );
            Response::success($result, 'Sugerencia de ubicación');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage());
        }
    }

    /**
     * POST /api/putaway/by-location
     * Mueve todo el stock de un bin a otro.
     * Body: { from_bin_id, to_bin_id }
     */
    public static function byLocation(array $params): void
    {
        $body = Request::body();
        $v = (new Validator($body))->required(['from_bin_id', 'to_bin_id']);

        if (!$v->passes()) {
            Response::error('Datos inválidos', 422, $v->errors());
            return;
        }

        try {
            $service = new PutawayService();
            $result = $service->putawayByLocation(
                (int) $body['from_bin_id'],
                (int) $body['to_bin_id'],
                AuthMiddleware::userId()
            );
            Response::success($result, 'Putaway por ubicación completado');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage());
        }
    }

    /**
     * POST /api/putaway/free
     * Modo libre: mover un item/cantidad específico entre bins.
     * Body: { item_id, batch_id?, from_bin_id, to_bin_id, quantity }
     */
    public static function free(array $params): void
    {
        $body = Request::body();
        $v = (new Validator($body))
            ->required(['item_id', 'from_bin_id', 'to_bin_id', 'quantity'])
            ->positiveNumber('quantity');

        if (!$v->passes()) {
            Response::error('Datos inválidos', 422, $v->errors());
            return;
        }

        try {
            $service = new PutawayService();
            $result = $service->freePutaway($body, AuthMiddleware::userId());
            Response::success($result, 'Putaway libre completado');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage());
        }
    }

    /**
     * POST /api/putaway
     * Crea tarea de putaway manual.
     * Body: { warehouse_id, item_id, batch_id?, from_bin_id, quantity }
     */
    public static function create(array $params): void
    {
        $body = Request::body();
        $v = (new Validator($body))
            ->required(['warehouse_id', 'item_id', 'from_bin_id', 'quantity'])
            ->positiveNumber('quantity');

        if (!$v->passes()) {
            Response::error('Datos inválidos', 422, $v->errors());
            return;
        }

        try {
            $service = new PutawayService();
            $taskId = $service->createPutawayTask(
                (int) $body['warehouse_id'],
                (int) $body['item_id'],
                isset($body['batch_id']) ? (int) $body['batch_id'] : null,
                (int) $body['from_bin_id'],
                (float) $body['quantity'],
                null,
                AuthMiddleware::userId()
            );
            Response::success(['task_id' => $taskId], 'Tarea de putaway creada', 201);
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage());
        }
    }

    /**
     * POST /api/putaway/{task_id}/confirm
     * Confirma putaway.
     * Body: { to_bin_id, confirmed_qty? }
     */
    public static function confirm(array $params): void
    {
        $body = Request::body();
        $v = (new Validator($body))->required(['to_bin_id']);

        if (!$v->passes()) {
            Response::error('Datos inválidos', 422, $v->errors());
            return;
        }

        try {
            $service = new PutawayService();
            $result = $service->confirmPutaway(
                (int) $params['task_id'],
                $body,
                AuthMiddleware::userId()
            );
            Response::success($result, 'Putaway confirmado');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage());
        }
    }
}
