<?php

namespace App\Models\Customers;

use App\Models\Concerns\Auditable;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Geo\City;
use App\Models\People\SalesRep;
use App\Models\Returns\ReturnDoc;
use App\Models\Sales\Invoice;
use App\Models\Sales\Transaction;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Customer extends Model
{
    use Auditable, BelongsToTenant, SoftDeletes;

    protected $fillable = [
        'uuid', 'business_name', 'phone', 'nic', 'email',
        'street_line1', 'street_line2', 'city_id', 'legacy_city',
        'assigned_rep_id', 'assigned_user_id', 'is_active',
    ];

    protected function casts(): array
    {
        return ['is_active' => 'boolean'];
    }

    protected static function booted(): void
    {
        static::creating(function (self $c): void {
            if (! $c->uuid) {
                $c->uuid = (string) Str::ulid();
            }
        });
    }

    public function contacts(): HasMany
    {
        return $this->hasMany(CustomerContact::class);
    }

    public function deliveryAddresses(): HasMany
    {
        return $this->hasMany(DeliveryAddress::class);
    }

    public function city(): BelongsTo
    {
        return $this->belongsTo(City::class);
    }

    public function rep(): BelongsTo
    {
        return $this->belongsTo(SalesRep::class, 'assigned_rep_id');
    }

    public function assignedUser(): BelongsTo
    {
        return $this->belongsTo(User::class, 'assigned_user_id');
    }

    public function creditBalance(): HasOne
    {
        return $this->hasOne(CustomerCreditBalance::class);
    }

    public function creditLedger(): HasMany
    {
        return $this->hasMany(CustomerCreditLedger::class);
    }

    public function invoices(): HasMany
    {
        return $this->hasMany(Invoice::class);
    }

    public function transactions(): HasMany
    {
        return $this->hasMany(Transaction::class);
    }

    public function returns(): HasMany
    {
        return $this->hasMany(ReturnDoc::class);
    }
}
