<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Helpers\Response;
use App\Services\ProductService;

class ProductController extends BaseController
{
    private ProductService $productService;

    public function __construct($request)
    {
        parent::__construct($request);
        $this->productService = new ProductService();
    }

    public function index(): void
    {
        $filters = [
            'search' => $this->request->query('search'),
            'status' => $this->request->query('status'),
            'category' => $this->request->query('category'),
        ];

        $page = (int) ($this->request->query('page', 1));
        $perPage = (int) ($this->request->query('per_page', 50));

        $result = $this->productService->getProducts($filters, $page, $perPage);

        Response::paginated(
            $result['items'],
            $result['total'],
            $result['page'],
            $result['per_page'],
            'Productos consultados correctamente'
        );
    }

    public function show(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $product = $this->productService->getProduct($id);
            Response::success($product, 'Producto consultado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function store(): void
    {
        $data = $this->request->body();

        $validation = $this->validate($data, function ($v) {
            $v->required('name', 'Nombre');
        });

        if ($validation->fails()) {
            Response::error($validation->firstError(), 422);
        }

        try {
            $product = $this->productService->createProduct($data);
            Response::created($product, 'Producto creado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function update(): void
    {
        $id = (int) $this->getRouteParam('id');
        $data = $this->request->body();

        try {
            $product = $this->productService->updateProduct($id, $data);
            Response::success($product, 'Producto actualizado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function destroy(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $this->productService->deleteProduct($id);
            Response::success(null, 'Producto eliminado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function toggleStatus(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $product = $this->productService->toggleStatus($id);
            $statusLabel = $product['status'] === 'active' ? 'activado' : 'desactivado';
            Response::success($product, "Producto {$statusLabel} correctamente");
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function getLeadProducts(): void
    {
        $leadId = (int) $this->getRouteParam('id');

        try {
            $products = $this->productService->getLeadProducts($leadId);
            Response::success($products, 'Productos del lead consultados correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function attachToLead(): void
    {
        $leadId = (int) $this->getRouteParam('id');
        $data = $this->request->body();

        if (empty($data['product_id'])) {
            Response::error('El producto es obligatorio', 422);
        }

        try {
            $products = $this->productService->attachToLead($leadId, (int) $data['product_id']);
            Response::success($products, 'Producto asociado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function detachFromLead(): void
    {
        $leadId = (int) $this->getRouteParam('id');
        $productId = (int) $this->getRouteParam('pid');

        try {
            $products = $this->productService->detachFromLead($leadId, $productId);
            Response::success($products, 'Producto desasociado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }
}
