<?php

namespace Modules\ClinicCore\Http\Controllers\Traits;

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

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

            $label = $attrs['patient_name']      ?? $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->_drmFilterAttrs($attrs);
                $changed   = array_keys($afterData);
            }
            if ($action === 'delete' && $beforeData === null) {
                $beforeData = $this->_drmFilterAttrs($attrs);
                $changed    = array_keys($beforeData);
            }

            EnhancedActivityLog::create([
                'user_id'        => auth()->id(),
                'business_id'    => (int) session('user.business_id'),
                'action'         => $action,
                'model_type'     => $this->_drmModelType($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('ClcActivityLog failed: ' . $e->getMessage());
        }
    }

    private function _drmModelType(Model $model): string
    {
        $map = [
            'Modules\ClinicCore\Entities\ClcPatient'              => 'clc_pet',
            'Modules\ClinicCore\Entities\ClcPatientContactDetail'   => 'clc_pet_owner',
            'Modules\ClinicCore\Entities\ClcAppointment'      => 'clc_appointment',
            'Modules\ClinicCore\Entities\ClcAppointmentNote'  => 'clc_appointment_note',
            'Modules\ClinicCore\Entities\ClcAppointmentDocument'   => 'clc_appointment_document',
            'Modules\ClinicCore\Entities\ClcAppointmentEditRequest' => 'clc_appointment_edit_request',
            'Modules\ClinicCore\Entities\ClcVaccination'      => 'clc_vaccination',
            'Modules\ClinicCore\Entities\ClcPrescription'     => 'clc_prescription',
            'Modules\ClinicCore\Entities\ClcDoctor'           => 'clc_doctor',
            'Modules\ClinicCore\Entities\ClcDepartment'       => 'clc_department',
            'Modules\ClinicCore\Entities\ClcVaccineType'      => 'clc_vaccine_type',
            'Modules\ClinicCore\Entities\ClcMedicalCondition' => 'clc_medical_condition',
            'Modules\ClinicCore\Entities\ClcMedicalReport'    => 'clc_medical_report',
            'Modules\ClinicCore\Entities\ClcBirthDeathRecord' => 'clc_birth_death_record',
            'Modules\ClinicCore\Entities\ClcEvaluation'       => 'clc_evaluation',
            'Modules\ClinicCore\Entities\ClcEvaluationQuestion' => 'clc_evaluation_question',
            'Modules\ClinicCore\Entities\ClcDoctorChangeRequest' => 'clc_doctor_change_request',
            'Modules\ClinicCore\Entities\ClcPreferredDoctorHistory' => 'clc_preferred_doctor_history',
        ];
        return $map[get_class($model)] ?? get_class($model);
    }

    private function _drmFilterAttrs(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);
    }
}
