<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\LeadTechnicalProblem;

class TechnicalProblemService
{
    private LeadTechnicalProblem $model;

    public function __construct()
    {
        $this->model = new LeadTechnicalProblem();
    }

    public function getByLead(int $leadId): array
    {
        return $this->model->findByLeadId($leadId);
    }

    public function create(int $leadId, string $description, int $userId): array
    {
        $id = $this->model->create([
            'lead_id' => $leadId,
            'description' => $description,
            'status' => 'pendiente',
            'created_by' => $userId,
        ]);

        return $this->model->findById($id);
    }

    public function update(int $id, string $description): array
    {
        $problem = $this->model->findById($id);
        if (!$problem) {
            throw new \RuntimeException('Problema técnico no encontrado', 404);
        }

        $this->model->update($id, ['description' => $description]);

        return $this->model->findById($id);
    }

    public function toggleStatus(int $id): array
    {
        $problem = $this->model->findById($id);
        if (!$problem) {
            throw new \RuntimeException('Problema técnico no encontrado', 404);
        }

        $newStatus = $problem['status'] === 'pendiente' ? 'resuelto' : 'pendiente';
        $updateData = ['status' => $newStatus];
        if ($newStatus === 'resuelto') {
            $updateData['resolved_at'] = date('Y-m-d H:i:s');
        } else {
            $updateData['resolved_at'] = null;
        }

        $this->model->update($id, $updateData);

        return $this->model->findById($id);
    }

    public function delete(int $id): void
    {
        $problem = $this->model->findById($id);
        if (!$problem) {
            throw new \RuntimeException('Problema técnico no encontrado', 404);
        }

        $this->model->delete($id);
    }
}
