<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

class Comment extends Model
{
    use HasFactory;

    protected $touches = ['ticket'];

    protected static ?bool $commentAttachmentColumnExists = null;

    protected $fillable = [
        'ticket_id', 'author_id', 'content', 'is_internal', 'is_first_response',
    ];

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

    protected $appends = ['message', 'user', 'isInternal', 'isFirstResponse'];

    public function ticket()
    {
        return $this->belongsTo(Ticket::class);
    }

    public function author()
    {
        return $this->belongsTo(User::class, 'author_id');
    }

    public function attachments()
    {
        if (!Attachment::supportsCommentAttachments()) {
            return $this->hasMany(Attachment::class, 'id', 'id')->whereRaw('1 = 0');
        }

        return $this->hasMany(Attachment::class);
    }

    public static function supportsAttachmentComments(): bool
    {
        if (self::$commentAttachmentColumnExists === null) {
            self::$commentAttachmentColumnExists = Attachment::supportsCommentAttachments();
        }

        return self::$commentAttachmentColumnExists;
    }

    public function getMessageAttribute()
    {
        return $this->content;
    }

    public function getUserAttribute()
    {
        return $this->relationLoaded('author') ? $this->getRelation('author') : null;
    }

    public function getIsInternalAttribute()
    {
        return (bool) ($this->attributes['is_internal'] ?? false);
    }

    public function getIsFirstResponseAttribute()
    {
        return (bool) ($this->attributes['is_first_response'] ?? false);
    }

    public function toArray()
    {
        $array = parent::toArray();
        $array['createdAt'] = $array['created_at'] ?? null;
        return $array;
    }
}
