<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Ticket extends Model
{
    use HasFactory;

    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'id', 'title', 'description', 'category', 'priority', 'status', 'requester', 'requester_id',
        'requester_name', 'department', 'assigned_to_id', 'sla_due', 'first_response_sla',
        'resolution_sla', 'first_response_at', 'first_response_met',
    ];

    protected function casts(): array
    {
        return [
            'sla_due' => 'datetime',
            'first_response_sla' => 'datetime',
            'resolution_sla' => 'datetime',
            'first_response_at' => 'datetime',
            'first_response_met' => 'boolean',
            'created_at' => 'datetime',
            'updated_at' => 'datetime',
        ];
    }

    protected $appends = [
        'requester_user', 'assigned_to',
        'requesterUser', 'assignedTo',
        'requesterName',
    ];

    public function agents()
    {
        return $this->belongsToMany(User::class, 'ticket_agent', 'ticket_id', 'agent_id')
            ->select(array_map(
                fn ($column) => str_starts_with($column, 'users.') ? $column : 'users.' . $column,
                User::supportDeskSelectColumns()
            ))
            ->withTimestamps();
    }

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

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

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function attachments()
    {
        return $this->hasMany(Attachment::class);
    }

    public function getRequesterUserAttribute()
    {
        if ($this->relationLoaded('requesterUserRelation')) {
            return $this->getRelation('requesterUserRelation');
        }
        if ($this->requester_id) {
            return User::find($this->requester_id);
        }
        return null;
    }

    public function getAssignedToAttribute()
    {
        if ($this->relationLoaded('assignedToRelation')) {
            return $this->getRelation('assignedToRelation');
        }
        if ($this->assigned_to_id) {
            return User::find($this->assigned_to_id);
        }
        return null;
    }

    // CamelCase accessors for frontend compatibility
    public function getRequesterNameAttribute()
    {
        return $this->attributes['requester_name'] ?? $this->attributes['requester'] ?? null;
    }

    public function toArray()
    {
        $array = parent::toArray();

        // Add camelCase aliases for frontend compatibility
        $array['slaDue'] = $array['sla_due'] ?? null;
        $array['firstResponseSLA'] = $array['first_response_sla'] ?? null;
        $array['resolutionSLA'] = $array['resolution_sla'] ?? null;
        $array['firstResponseAt'] = $array['first_response_at'] ?? null;
        $array['firstResponseMet'] = (bool) ($array['first_response_met'] ?? false);
        $array['createdAt'] = $array['created_at'] ?? null;
        $array['updatedAt'] = $array['updated_at'] ?? null;

        // Include agents if loaded
        if ($this->relationLoaded('agents')) {
            $array['agents'] = $this->agents->toArray();
        }

        return $array;
    }
}
