<?php

namespace App\Services\Opportunity;

use Exception;
use App\Http\Messages\ExeptionMessages;
use App\Repositories\Customer\CustomerRepositoryInterface;
use App\Http\Resources\Opportunity\KanbanOpportunityResource;
use App\Repositories\Opportunity\OpportunityRepositoryInterface;

class OpportunityService
{
    protected $opportunityRepository;
    protected $customerRepository;
    public function __construct(OpportunityRepositoryInterface $opportunityRepositoryInterface, CustomerRepositoryInterface $customerRepositoryInterface)
    {
        $this->opportunityRepository = $opportunityRepositoryInterface;
        $this->customerRepository = $customerRepositoryInterface;
    }
    public function getAllOpportunities(){
        return $this->opportunityRepository->getAllOpportunities();
    }
    public function getOpportunityById($id){
        return $this->opportunityRepository->getOpportunityById($id);
    }
    public function createOpportunity($customer,$data){
        return $this->opportunityRepository->createOpportunity($customer,$data)->refresh();
    }
    public function checkActiveOpportunityForCustomer($customerId){
        $customer = $this->customerRepository->find($customerId)
        ?? throw new Exception(ExeptionMessages::CUSTOMER_NOT_FOUND, 404);
        !$this->opportunityRepository->getActiveOpportunityForCustomer($customerId)
        ?: throw new Exception(ExeptionMessages::CUSTOMER_HAS_OPPORTUNITY_ACTIVE, 409);
        return $customer;
    }
    public function getAllOpportunityWithPaginate($request){
        $query = $this->opportunityRepository->query();
        $itemsPerPage = $request->input('itemsPerPage', 10);
        $page = $request->input('page', 1);
        return  $query->paginate($itemsPerPage,['*'],'page',$page);
    }
    public function updateOpportunity($id,$data){
        $opportunity = $this->opportunityRepository->getOpportunityById($id);
        if (!$opportunity) {
            throw new Exception(ExeptionMessages::OPPORTUNITY_NOT_FOUND, 404);
        }
        return $this->opportunityRepository->updateOpportunity($id,$data)->refresh();
    }
    public function allOportunityForUsers($userId){
        return $this->opportunityRepository->getAllOportunitiesForUser($userId);
    }
    public function allOportunityKanban($userId){
        $opportunities = $this->opportunityRepository->getAllOportunitiesForUser($userId);
        return new KanbanOpportunityResource($opportunities);
    }
    public function convertOpportunityProspect($opportunityId,$data){
        if($this->opportunityRepository->isProspectOpportunity($opportunityId)){
            throw new Exception(ExeptionMessages::OPPORTUNITY_IS_PROSPECT, 400);
        }
        return $this->opportunityRepository->convertOpportunityToProspect($opportunityId,$data);
    }
    public function changeStatus($id, $stage_id){
      return  $this->opportunityRepository->changeStage($id, $stage_id);
    }
}
