<?php

namespace App\Models;

use App\Models\Traits\HasHexId;
use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    use HasHexId {
        toArray as hexIdToArray;
    }

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

    protected $fillable = [
        'id', 'title', 'description', 'created_by', 'assigned_to',
        'status', 'priority', 'access', 'due_at', 'completed_at', 'organization_id',
    ];

    protected $casts = [
        'due_at' => 'datetime',
        'completed_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'access' => 'string',
    ];

    public function organization()
    {
        return $this->belongsTo(Organization::class, 'organization_id', 'id');
    }

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

    public function assignedTo()
    {
        return $this->belongsTo(User::class, 'assigned_to', 'id');
    }

    public function toArray()
    {
        $data = $this->hexIdToArray();
        if (array_key_exists('organization_id', $data)) {
            $data['organization_id'] = (string)($this->formatBinaryToHex($this->attributes['organization_id'] ?? null) ?? $data['organization_id']);
        }
        if (array_key_exists('created_by', $data)) {
            $data['created_by'] = (string)($this->formatBinaryToHex($this->attributes['created_by'] ?? null) ?? $data['created_by']);
        }
        if (array_key_exists('assigned_to', $data)) {
            $data['assigned_to'] = (string)($this->formatBinaryToHex($this->attributes['assigned_to'] ?? null) ?? $data['assigned_to']);
        }
        return $data;
    }
}
