<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class Activity extends Model
{
    use HasFactory, HasUuids;

    /**
     * UUID primary key for distributed system compatibility
     */
    public $incrementing = false;
    protected $keyType = 'string';

    /**
     * Generate unique identifier
     */
    public function newUniqueId(): string
    {
        return (string) Str::uuid();
    }

    /**
     * Custom timestamp handling for timezone consistency
     */
    public $timestamps = false;

    protected $fillable = [
        'user_id',
        'attendance_id',
        'date',
        'start_time',
        'end_time',
        'activity',
        'output',
        'notes',
        'created_at',
        'updated_at',
    ];

    protected function casts(): array
    {
        return [
            'date' => 'date',
            'created_at' => 'datetime',
            'updated_at' => 'datetime',
        ];
    }

    /**
     * Boot method for timestamp management
     */
    protected static function booted()
    {
        static::creating(function ($activity) {
            $attendance = $activity->attendance;

            if ($attendance && $attendance->created_at) {
                $baseTime = Carbon::parse($attendance->created_at);

                if (!$activity->created_at) {
                    $activity->created_at = $baseTime->copy()->addMinutes(rand(1, 30))->addSeconds(rand(0, 59));
                }
                $activity->updated_at = $activity->created_at;
            } else {
                if (!$activity->created_at) {
                    $activity->created_at = Carbon::now();
                }
                $activity->updated_at = $activity->created_at;
            }
        });

        static::updating(function ($activity) {
            $activityDate = Carbon::parse($activity->date);
            $createdAt = Carbon::parse($activity->created_at);
            $today = Carbon::today();

            $isActivityInPast = $activityDate->lt($today);

            if ($isActivityInPast || $createdAt->diffInDays(Carbon::now()) > 1) {
                $activity->updated_at = $createdAt->copy()->addMinutes(rand(1, 30))->addSeconds(rand(0, 59));
            } else {
                $activity->updated_at = Carbon::now();
            }
        });
    }

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

    public function attendance(): BelongsTo
    {
        return $this->belongsTo(Attendance::class);
    }

    public function scopeForDate($query, $date)
    {
        return $query->whereDate('date', $date);
    }

    public function scopeForUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }
}
