﻿<?php

namespace App\Models;

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

class JobDescriptionActivityLog extends Model
{
    use HasFactory;

    protected $table = 'job_description_activity_log';
    
    const UPDATED_AT = null;

    protected $fillable = [
        'job_description_id',
        'user_id',
        'event',
        'meta',
    ];

    protected $casts = [
        'meta'       => 'array',
        'created_at' => 'datetime',
    ];

    // Event Constants

    const EVENT_DRAFT_CREATED          = 'draft_created';
    const EVENT_AI_GENERATION_COMPLETE = 'ai_generation_complete';
    const EVENT_SECTION_EDITED         = 'section_edited';
    const EVENT_SECTION_REGENERATED    = 'section_regenerated';
    const EVENT_CUSTOM_SECTION_ADDED   = 'custom_section_added';
    const EVENT_CUSTOM_SECTION_DELETED = 'custom_section_deleted';
    const EVENT_VALIDATION_RUN         = 'validation_run';
    const EVENT_VALIDATION_PASSED      = 'validation_passed';
    const EVENT_VALIDATION_FAILED      = 'validation_failed';
    const EVENT_APPROVED               = 'approved';
    const EVENT_SAVED_AS_DRAFT         = 'saved_as_draft';
    const EVENT_SENT_BACK              = 'sent_back';
    const EVENT_PUBLISHED              = 'published';

    // Human-readable descriptions for the preview page activity feed
    const EVENT_LABELS = [
        self::EVENT_DRAFT_CREATED          => 'Draft created',
        self::EVENT_AI_GENERATION_COMPLETE => 'AI generation complete',
        self::EVENT_SECTION_EDITED         => 'Section edited manually',
        self::EVENT_SECTION_REGENERATED    => 'Section regenerated by AI',
        self::EVENT_CUSTOM_SECTION_ADDED   => 'Custom section added',
        self::EVENT_CUSTOM_SECTION_DELETED => 'Custom section deleted',
        self::EVENT_VALIDATION_RUN         => 'Validation run',
        self::EVENT_VALIDATION_PASSED      => 'Validation passed',
        self::EVENT_VALIDATION_FAILED      => 'Validation completed with issues',
        self::EVENT_APPROVED               => 'Job description approved',
        self::EVENT_SAVED_AS_DRAFT         => 'Reverted to draft',
        self::EVENT_SENT_BACK              => 'Sent back for revision',
        self::EVENT_PUBLISHED              => 'Job description published',
    ];

    // Relationships

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

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

    // Helpers

    public function label(): string
    {
        return self::EVENT_LABELS[$this->event] ?? ucfirst(str_replace('_', ' ', $this->event));
    