<?php

namespace App\Services;

use App\DTOs\SuperAdmin\SectionRuleDto;
use App\Models\SectionRule;
use Exception;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

class SectionRuleService
{
    public function getAll(): Collection
    {
        return SectionRule::all();
    }

    public function getPaginated(int $perPage = 10): LengthAwarePaginator
    {
        return SectionRule::orderBy('created_at', 'desc')->paginate($perPage);
    }

    public function create(SectionRuleDto $dto): ?SectionRule
    {
        try {
            return SectionRule::create([
                'key' => $dto->key,
                'label' => $dto->label,
                'options' => $dto->options,
                'default' => $dto->default,
            ]);
        } catch (Exception $e) {
            Log::error('Error al crear SectionRule: '.$e->getMessage(), [
                'data' => $dto,
                'trace' => $e->getTraceAsString(),
            ]);
            return null;
        }
    }

    public function find(int $id): ?SectionRuleDto
    {
        try {
            $rule = SectionRule::findOrFail($id);

            return new SectionRuleDto($rule->toArray());
        } catch (Exception $e) {
            Log::error('No se pudo encontrar SectionRule: '.$e->getMessage(), [
                'id' => $id,
                'trace' => $e->getTraceAsString(),
            ]);
            return null;
        }
    }

    public function update(int $id, SectionRuleDto $dto): bool
    {
        try {
            $rule = SectionRule::findOrFail($id);

            $rule->update([
                'key' => $dto->key,
                'label' => $dto->label,
                'options' => $dto->options,
                'default' => $dto->default,
            ]);

            return true;
        } catch (Exception $e) {
            Log::error('Error al actualizar SectionRule: '.$e->getMessage(), [
                'id' => $id,
                'data' => $dto,
                'trace' => $e->getTraceAsString(),
            ]);
            return false;
        }
    }

    public function delete(int $id): bool
    {
        try {
            $rule = SectionRule::findOrFail($id);
            $rule->delete();
            return true;
        } catch (Exception $e) {
            Log::error('Error al eliminar SectionRule: '.$e->getMessage(), [
                'id' => $id,
                'trace' => $e->getTraceAsString(),
            ]);
            return false;
        }
    }
}