<?php

namespace App\Http\Controllers\Api\V1\Showroom;

use App\Http\Controllers\Controller;
use App\Services\Showroom\ShowroomCustomerService;
use Illuminate\Http\Request;

class CustomerController extends Controller
{
    public function __construct(private readonly ShowroomCustomerService $customerService)
    {
    }

    public function search(Request $request)
    {
        $request->validate(['mobile' => 'required|string|max:40']);
        $customer = $this->customerService->findByMobile($request->mobile);

        return response()->json([
            'found' => (bool) $customer,
            'customer' => $customer ? $this->payload($customer) : null,
        ]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'mobile' => 'required|string|max:40',
            'name' => 'required|string|max:191',
        ]);

        $customer = $this->customerService->findOrCreateByMobile($data['mobile'], $data['name']);

        return response()->json($this->payload($customer), 201);
    }

    private function payload($customer): array
    {
        return [
            'id' => $customer->id,
            'name' => $customer->name ?: trim($customer->f_name . ' ' . $customer->l_name),
            'mobile' => $customer->phone,
            'wallet_balance' => (float) ($customer->wallet_balance ?? 0),
            'point_balance' => (int) ($customer->loyalty_point ?? 0),
        ];
    }
}
