<?php

namespace App\Services;

use App\Http\Resources\SegmentResource;
use App\Models\Company;
use App\Models\Segment;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\DB;

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

    public function list($params, $withPagination)
    {
        $segments = Segment::segmentFilters()->orderBy('id', 'desc');

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

        $segments = SegmentResource::collection($segments->load('company'));

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

    public function register($params)
    {
        DB::beginTransaction();
        try {
            #Validar empresa
            $company = Company::activeForID($params['idcompany'])->first();
            if (!$company) return $this->errorResponse('La empresa seleccionada no es válida.', 400);

            #Validar duplicidad de nombre
            $name = Segment::where('name', $params['name'])->active()->company()->first();
            if ($name) return $this->errorResponse('El nombre ingresado ya se encuentra registrado.', 400);

            $segment = Segment::create([
                'name' => $params['name'],
                'description' => $params['description'] ?? null,
                'idcompany' => $params['idcompany']
            ]);
            $segment->save();
    
            DB::commit();
            return $this->successResponse('Segmento registrado satisfactoriamente.', $segment);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la creación de un segmento.', $th->getMessage());
        }
    }

    public function update($id, $params)
    {
        DB::beginTransaction();
        try {
            #Validar empresa
            $company = Company::activeForID($params['idcompany'])->first();
            if (!$company) return $this->errorResponse('La empresa seleccionada no es válida.', 400);

            #Validar segmento
            $segment = Segment::activeForID($id)->company()->first();
            if (!$segment) return $this->errorResponse('Segmento no válido.', 400);

            #Validar duplicidad de nombre
            $name = Segment::where('id', '!=', $id)->where('name', $params['name'])->company()->active()->first();
            if ($name) return $this->errorResponse('El nombre ingresado ya se encuentra registrado.', 400);

            $segment->update($params);
            $segment->save();

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

    public function delete($id)
    {
        DB::beginTransaction();
        try {
            #Validar segmento
            $segment = Segment::activeForID($id)->company()->first();
            if (!$segment) return $this->errorResponse('Segmento no válida.', 400);

            $segment->status = 2;
            $segment->save();

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