<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Helpers\Response;
use App\Services\TechnicalProblemService;

class TechnicalProblemController extends BaseController
{
    private TechnicalProblemService $service;

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

    public function index(): void
    {
        $leadId = (int) $this->getRouteParam('id');
        $problems = $this->service->getByLead($leadId);
        Response::success($problems, 'Problemas técnicos consultados correctamente');
    }

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

        if (empty($data['description'])) {
            Response::error('La descripción es obligatoria', 422);
            return;
        }

        try {
            $problem = $this->service->create($leadId, $data['description'], $this->getAuthUserId());
            Response::created($problem, 'Problema técnico registrado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

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

        if (empty($data['description'])) {
            Response::error('La descripción es obligatoria', 422);
            return;
        }

        try {
            $problem = $this->service->update($id, $data['description']);
            Response::success($problem, 'Problema técnico actualizado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

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

        try {
            $problem = $this->service->toggleStatus($id);
            Response::success($problem, 'Estado actualizado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

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

        try {
            $this->service->delete($id);
            Response::success([], 'Problema técnico eliminado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }
}
