<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class SupportTicket extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'ticket_reference',
        'customer_email',
        'subject',
        'status',
        'priority',
        'department',
        'last_reply_at',
    ];

    /** @return array<string, string> */
    protected function casts(): array
    {
        return [
            'last_reply_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::created(function (SupportTicket $ticket): void {
            if (empty($ticket->ticket_reference)) {
                $ticket->updateQuietly([
                    'ticket_reference' => sprintf(
                        config('tickets.ticket_reference_format'),
                        $ticket->id
                    ),
                ]);
            }
        });
    }

    public function scopeByReference(Builder $query, string $reference): Builder
    {
        return $query->where('ticket_reference', $reference);
    }

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

    public function replies(): HasMany
    {
        return $this->hasMany(TicketReply::class, 'ticket_id');
    }
}
