<?php

namespace App\Core\Services\Customer;

use App\Core\Repositories\CustomerRepository;
use App\Models\Customer;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

/**
 * Customer Service
 * Handles all customer business logic
 */
class CustomerService
{
    public function __construct(
        private CustomerRepository $customerRepository
    ) {}

    /**
     * Create a new customer
     */
    public function create(array $data): Customer
    {
        DB::beginTransaction();

        try {
            // Hash password if provided
            if (isset($data['password']) && ! empty($data['password'])) {
                $data['password'] = Hash::make($data['password']);
            } else {
                // Remove password if empty (for customers without portal access)
                unset($data['password']);
            }

            // Set created_by if not set
            if (! isset($data['created_by'])) {
                $data['created_by'] = auth()->id();
            }

            $customer = $this->customerRepository->create($data);

            DB::commit();

            return $customer;
        } catch (Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    /**
     * Update a customer
     */
    public function update(Customer $customer, array $data): bool
    {
        DB::beginTransaction();

        try {
            // Hash password if provided
            if (isset($data['password']) && ! empty($data['password'])) {
                $data['password'] = Hash::make($data['password']);
            } else {
                // Don't update password if not provided
                unset($data['password']);
            }

            $result = $this->customerRepository->update($customer, $data);

            DB::commit();

            return $result;
        } catch (Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    /**
     * Delete a customer
     */
    public function delete(Customer $customer): bool
    {
        return $this->customerRepository->delete($customer);
    }
}
