<?php

namespace App\Services;

use App\Http\Resources\CompanyConfigurationResource;
use App\Models\CompanyConfiguration;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\DB;

class CompanyConfigurationService
{
    use HasResponse;

    public function list($withPagination)
    {
        $company = CompanyConfiguration::companyConfigurationFilters() # Filtrado por el modelo
            ->orderBy('id', 'desc');

        $company = !empty($withPagination)
            ? $company->paginate($withPagination['perPage'], page: $withPagination['page'])
            : $company->get();

        return $this->successResponse('Lectura exitosa.', CompanyConfigurationResource::collection($company));
    }

    public function update($params)
    {
        DB::beginTransaction();
        try {
            # Verificar validez de la compañía
            $validate = $this->verifyCompanyConfiguration($params['idcompany']);
            if (!$validate->original['status']) return $validate;

            $idconfiguration = $validate->original['data']['detail'];

            $company = CompanyConfiguration::find($idconfiguration);
            $company->update($params);

            DB::commit();
            return $this->successResponse('Configuración actualizada satisfactoriamente.', $company);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la actualización de configuración.', $th->getMessage());
        }
    }

    private function verifyCompanyConfiguration($idCompany)
    {
        $companyConfiguration = CompanyConfiguration::where('idcompany', $idCompany)->active()->first();
        if (!$companyConfiguration) return $this->errorResponse('La configuración de la compañía no existe', 400);

        return $this->successResponse('OK', $companyConfiguration->id);
    }
}
