<?php

namespace App\Services;

use App\Http\Resources\ReferenceDocumentsResource;
use App\Models\CustomerReferenceDocument;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\DB;

/**
 * Class ReferenceDocumentsService
 * @package App\Services
 */
class ReferenceDocumentsService
{
    use HasResponse;

    public function list($withPagination)
    {
        $documents = CustomerReferenceDocument::referenceDocumentsFilters() # Filtrado por el modelo
            ->orderBy('id', 'desc');

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

        $documents = ReferenceDocumentsResource::collection($documents->load('documentofsale', 'customer', 'company'));

        return $this->successResponse('Lectura exitosa.', $documents);
    }

    public function register($params)
    {
        DB::beginTransaction();
        try {
            # Verificar duplicidad
            $existing = CustomerReferenceDocument::where('iddocument_of_sale', $params['iddocument_of_sale'])->where('idcustomer', $params['idcustomer'])->where('idcompany', $params['idcompany'])->where('status', 1)->first();
            if ($existing) return $this->errorResponse('El tipo de documento ya se encuentra registrado.', 400);

            $document = CustomerReferenceDocument::create([
                'folio' => $params['folio'],
                'description' => $params['description'],
                'iddocument_of_sale' => $params['iddocument_of_sale'],
                'idcustomer' => $params['idcustomer'],
                'idcompany' => $params['idcompany']
            ]);
            $document->fresh();

            DB::commit();
            return $this->successResponse('Documento asignado satisfactoriamente.', $document);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la asignación de un documento.', $th->getMessage());
        }
    }

    public function update($id, $params)
    {
        DB::beginTransaction();
        try {
            # Verificar validez del vendedor
            $validate = $this->verifyDocument($id, $params['rut']);
            if (!$validate->original['status']) return $validate;

            $salesman = CustomerReferenceDocument::find($id);
            $salesman->update($params);

            DB::commit();
            return $this->successResponse('Vendedor actualizado satisfactoriamente.', $salesman);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la actualización de un vendedor.', $th->getMessage());
        }
    }

    public function delete($id)
    {
        DB::beginTransaction();
        try {
            # Verificar validez del conductor
            $validate = $this->verifyDocument($id);
            if (!$validate->original['status']) return $validate;

            $document = CustomerReferenceDocument::find($id);
            $document->update(['status' => 2]);

            DB::commit();
            return $this->successResponse('Documento eliminado de la asignación satisfactoriamente.', $document);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la eliminación de un documento.', $th->getMessage());
        }
    }

    private function verifyDocument($id, $rut = null)
    {
        $document = CustomerReferenceDocument::activeForID($id)->first();
        if (!$document) return $this->errorResponse('El tipo de documento seleccionado no esta disponible', 400);
        return $this->successResponse('OK');
    }
}
