<?php

namespace Modules\Vrc\Services\Adapters\Erp;

use App\Contact;
use Illuminate\Support\Str;
use Modules\Vrc\Services\Contracts\ContactServiceContract;

/**
 * ERP adapter: reuses App\Contact (type=customer) for VRC. Customers are
 * de-duplicated within a business by mobile, then email. Mirrors the BMS
 * ErpContactService.
 */
class ErpContactService implements ContactServiceContract
{
    public function find(int $businessId, int $contactId)
    {
        return Contact::where('business_id', $businessId)->find($contactId);
    }

    public function findOrCreateCustomer(int $businessId, array $attrs)
    {
        $phone = $attrs['phone'] ?? null;
        $email = $attrs['email'] ?? null;

        $existing = Contact::where('business_id', $businessId)
            ->where(function ($q) use ($phone, $email) {
                if (! empty($phone)) {
                    $q->orWhere('mobile', $phone);
                }
                if (! empty($email)) {
                    $q->orWhere('email', $email);
                }
            })
            ->when(empty($phone) && empty($email), fn ($q) => $q->whereRaw('1 = 0'))
            ->first();

        if ($existing) {
            return $existing;
        }

        $name = trim($attrs['name'] ?? '') ?: 'Walk-in Customer';

        return Contact::create([
            'business_id'    => $businessId,
            'type'           => 'customer',
            'name'           => $name,
            'first_name'     => $name,
            'mobile'         => $phone,
            'email'          => $email,
            'contact_id'     => 'VRC-' . strtoupper(Str::random(8)),
            'contact_status' => 'active',
            'created_by'     => $this->createdBy($businessId),
            'crm_source'     => $attrs['source'] ?? null,
        ]);
    }

    public function customersDropdown(int $businessId): array
    {
        // Reuse the ERP helper; returns [id => name] (no "none", no id suffix).
        return Contact::customersDropdown($businessId, false, false)->toArray();
    }

    public function name(int $businessId, int $contactId): string
    {
        $contact = $this->find($businessId, $contactId);
        return $contact ? (string) $contact->name : '';
    }

    /** Resolve a non-null created_by for system-created contacts. */
    protected function createdBy(int $businessId): ?int
    {
        return auth()->id()
            ?? optional(\App\Business::find($businessId))->owner_id
            ?? \App\User::where('business_id', $businessId)->min('id');
    }
}
