<?php

namespace App\Domains\Conversations\Models;

use App\Domains\Channels\Models\ChannelAccount;
use App\Domains\Contacts\Models\Contact;
use App\Domains\Leads\Models\Lead;
use App\Domains\Tenancy\Models\Branch;
use App\Domains\Tenancy\Models\Tenant;
use App\Models\User;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Conversation extends Model
{
    use HasFactory;
    use HasUuids;

    protected $fillable = [
        'tenant_id',
        'branch_id',
        'contact_id',
        'channel_account_id',
        'channel_type',
        'external_thread_id',
        'assigned_user_id',
        'status',
        'priority',
        'unread_count',
        'first_response_at',
        'last_message_at',
        'closed_at',
    ];

    protected $casts = [
        'first_response_at' => 'datetime',
        'last_message_at' => 'datetime',
        'closed_at' => 'datetime',
    ];

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

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

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

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

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

    public function messages(): HasMany
    {
        return $this->hasMany(Message::class)->orderBy('created_at');
    }

    public function notes(): HasMany
    {
        return $this->hasMany(InternalNote::class)->orderByDesc('created_at');
    }

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