<?php

namespace App\Models;

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

class TicketActivity extends Model
{
    use HasFactory;

    protected $fillable = [
        'ticket_id',
        'user_id',
        'action',
        'field',
        'old_value',
        'new_value',
        'description',
    ];

    /**
     * Activity types
     */
    const ACTION_CREATED = 'created';
    const ACTION_UPDATED = 'updated';
    const ACTION_ASSIGNED = 'assigned';
    const ACTION_STATUS_CHANGED = 'status_changed';
    const ACTION_PRIORITY_CHANGED = 'priority_changed';
    const ACTION_COMMENTED = 'commented';
    const ACTION_ATTACHMENT_ADDED = 'attachment_added';
    const ACTION_RESOLVED = 'resolved';
    const ACTION_CLOSED = 'closed';
    const ACTION_REOPENED = 'reopened';

    /**
     * Get the ticket this activity belongs to
     */
    public function ticket()
    {
        return $this->belongsTo(Ticket::class);
    }

    /**
     * Get the user who performed this activity
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get formatted activity description
     */
    public function getFormattedDescription()
    {
        if ($this->description) {
            return $this->description;
        }

        switch ($this->action) {
            case self::ACTION_CREATED:
                return 'Ticket creado';
            case self::ACTION_ASSIGNED:
                return 'Ticket asignado a ' . ($this->new_value ? User::find($this->new_value)?->name : 'nadie');
            case self::ACTION_STATUS_CHANGED:
                return 'Estado cambiado de "' . $this->old_value . '" a "' . $this->new_value . '"';
            case self::ACTION_PRIORITY_CHANGED:
                return 'Prioridad cambiada de "' . $this->old_value . '" a "' . $this->new_value . '"';
            case self::ACTION_COMMENTED:
                return 'Comentario agregado';
            case self::ACTION_ATTACHMENT_ADDED:
                return 'Archivo adjunto agregado';
            case self::ACTION_RESOLVED:
                return 'Ticket marcado como resuelto';
            case self::ACTION_CLOSED:
                return 'Ticket cerrado';
            case self::ACTION_REOPENED:
                return 'Ticket reabierto';
            default:
                return 'Actividad: ' . $this->action;
        }
    }

    /**
     * Create activity log
     */
    public static function log($ticketId, $userId, $action, $field = null, $oldValue = null, $newValue = null, $description = null)
    {
        return self::create([
            'ticket_id' => $ticketId,
            'user_id' => $userId,
            'action' => $action,
            'field' => $field,
            'old_value' => $oldValue,
            'new_value' => $newValue,
            'description' => $description,
        ]);
    }
}