<?php

namespace App\Services;

use App\Http\Resources\BusinessAreaResource;
use App\Models\BusinessArea;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\DB;

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

    public function list($withPagination)
    {
        $areas = BusinessArea::businessAreaFilters() # Filtrado por el modelo
            ->orderBy('id', 'desc');

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

        $areas = BusinessAreaResource::collection($areas->load('branchOffice', 'company'));

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

    public function register($params)
    {
        DB::beginTransaction();
        try {
            # Verificar duplicidad de nombre
            $nameExisting = BusinessArea::name($params['name'])->first();
            if ($nameExisting) return $this->errorResponse('El nombre ya se encuentra registrado.', 400);

            $area = BusinessArea::create([
                'name'           => $params['name'],
                'description'    => $params['description'],
                'idbranchoffice' => $params['idbranchoffice'],
                'idcompany'      => $params['idcompany']
            ]);
            $area->fresh();

            DB::commit();
            return $this->successResponse('Area de negocio creado satisfactoriamente.', $area);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la creación de un Area de negocio.', $th->getMessage());
        }
    }

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

            $area = BusinessArea::find($id);
            $area->update($params);

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

    public function changeStatus($id, $params)
    {
        DB::beginTransaction();
        try {
            # Verificar validez de la bodega
            $validate = $this->verifyBusinessArea($id);
            if (!$validate->original['status']) return $validate;

            if($params['status'] == '2') return $this->successResponse('Solo se puede habilitar o deshabilitar.');

            $area = BusinessArea::find($id);
            $area->status = $params['status'];
            $area->save();

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

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

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

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

    private function verifyBusinessArea($id)
    {
        $area = BusinessArea::activeForID($id)->first();
        if (!$area) return $this->errorResponse('El Area de negocio seleccionado no esta disponible', 400);

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