<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class SupportTicket extends Model
{
    protected $guarded = ['id', 'created_at', 'updated_at'];

    protected $casts = [
        'closed_at' => 'datetime',
        'attachments' => 'array',
    ];

    public const STATUS_OPEN = 'open';
    public const STATUS_CLOSED = 'closed';
    public const STATUS_READ = 'read';
    public const STATUS_UNREAD = 'unread';

    public const CATEGORY_FINANCIAL = 'financial';
    public const CATEGORY_PROJECT = 'project';
    public const CATEGORY_TECHNICAL = 'technical';
    public const CATEGORY_OTHER = 'other';

    protected static function boot(): void
    {
        parent::boot();
        static::creating(function (SupportTicket $ticket): void {
            if (empty($ticket->code)) {
                $ticket->code = 'T' . strtoupper(Str::random(8));
            }
            if (empty($ticket->created_by) && auth()->check()) {
                $ticket->created_by = auth()->id();
            }
        });
    }

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

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

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

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

    public function getRouteKeyName(): string
    {
        return 'code';
    }

    public static function categoryOptions(): array
    {
        return [
            self::CATEGORY_FINANCIAL => 'مالی',
            self::CATEGORY_PROJECT => 'پروژه',
            self::CATEGORY_TECHNICAL => 'فنی',
            self::CATEGORY_OTHER => 'سایر',
        ];
    }

    public static function statusOptions(): array
    {
        return [
            self::STATUS_OPEN => 'باز',
            self::STATUS_CLOSED => 'بسته',
            self::STATUS_READ => 'خوانده شده',
            self::STATUS_UNREAD => 'خوانده نشده',
        ];
    }
}
