<?php

namespace Modules\VetClinic\Http\Controllers\Traits;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Modules\ActivityLog\Entities\EnhancedActivityLog;

/**
 * Provides lightweight activity logging for VetClinic controllers.
 * Uses EnhancedActivityLog directly so module-specific model types
 * appear in the global activity log with 'vc_*' prefixes.
 */
trait LogsVcActivity
{
    protected function vcLog(string $action, Model $model, array $extra = []): void
    {
        try {
            $attrs = $model->getAttributes();

            $label = $attrs['petname']      ?? $attrs['name']         ?? $attrs['ref_no']
                  ?? $attrs['report_title'] ?? $attrs['document_name'] ?? ('#' . $model->getKey());

            $afterData  = $extra['after']  ?? null;
            $beforeData = $extra['before'] ?? null;
            $changed    = $extra['fields'] ?? [];

            if ($action === 'create' && $afterData === null) {
                $afterData = $this->_vcFilterAttrs($attrs);
                $changed   = array_keys($afterData);
            }
            if ($action === 'delete' && $beforeData === null) {
                $beforeData = $this->_vcFilterAttrs($attrs);
                $changed    = array_keys($beforeData);
            }

            EnhancedActivityLog::create([
                'user_id'        => auth()->id(),
                'business_id'    => (int) session('user.business_id'),
                'action'         => $action,
                'model_type'     => $this->_vcModelType($model),
                'model_id'       => $model->getKey(),
                'model_label'    => (string) $label,
                'before_data'    => $beforeData,
                'after_data'     => $afterData,
                'changed_fields' => $changed,
                'request_url'    => Str::limit(request()->fullUrl(), 490),
                'request_method' => request()->method(),
                'ip_address'     => request()->ip(),
                'user_agent'     => Str::limit(request()->userAgent() ?? '', 490),
                'request_id'     => (string) Str::uuid(),
                'is_primary'     => 1,
            ]);
        } catch (\Throwable $e) {
            \Illuminate\Support\Facades\Log::warning('VcActivityLog failed: ' . $e->getMessage());
        }
    }

    private function _vcModelType(Model $model): string
    {
        $map = [
            'Modules\VetClinic\Entities\VcPet'              => 'vc_pet',
            'Modules\VetClinic\Entities\VcPetOwnerDetail'   => 'vc_pet_owner',
            'Modules\VetClinic\Entities\VcAppointment'      => 'vc_appointment',
            'Modules\VetClinic\Entities\VcAppointmentNote'  => 'vc_appointment_note',
            'Modules\VetClinic\Entities\VcAppointmentDocument'   => 'vc_appointment_document',
            'Modules\VetClinic\Entities\VcAppointmentEditRequest' => 'vc_appointment_edit_request',
            'Modules\VetClinic\Entities\VcVaccination'      => 'vc_vaccination',
            'Modules\VetClinic\Entities\VcPrescription'     => 'vc_prescription',
            'Modules\VetClinic\Entities\VcDoctor'           => 'vc_doctor',
            'Modules\VetClinic\Entities\VcDepartment'       => 'vc_department',
            'Modules\VetClinic\Entities\VcVaccineType'      => 'vc_vaccine_type',
            'Modules\VetClinic\Entities\VcMedicalCondition' => 'vc_medical_condition',
            'Modules\VetClinic\Entities\VcMedicalReport'    => 'vc_medical_report',
            'Modules\VetClinic\Entities\VcBirthDeathRecord' => 'vc_birth_death_record',
            'Modules\VetClinic\Entities\VcEvaluation'       => 'vc_evaluation',
            'Modules\VetClinic\Entities\VcEvaluationQuestion' => 'vc_evaluation_question',
            'Modules\VetClinic\Entities\VcDoctorChangeRequest' => 'vc_doctor_change_request',
            'Modules\VetClinic\Entities\VcPreferredDoctorHistory' => 'vc_preferred_doctor_history',
        ];
        return $map[get_class($model)] ?? get_class($model);
    }

    private function _vcFilterAttrs(array $attrs): array
    {
        $skip = ['password', 'remember_token', 'created_at', 'updated_at', 'deleted_at'];
        return array_filter($attrs, fn($k) => !in_array($k, $skip, true), ARRAY_FILTER_USE_KEY);
    }
}
