<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Activity extends Model
{
    protected $keyType = 'string';
    public $incrementing = false;

    // ── Typen ─────────────────────────────────────────────────────────────
    const TYPE_EVENT_CREATED       = 'event_created';
    const TYPE_EVENT_UPDATED       = 'event_updated';
    const TYPE_EVENT_DELETED       = 'event_deleted';
    const TYPE_REMINDER_SENT       = 'reminder_sent';
    const TYPE_AUTOMATION_TRIGGERED = 'automation_triggered';
    const TYPE_CONTACT_CREATED     = 'contact_created';
    const TYPE_CONTACT_UPDATED     = 'contact_updated';
    const TYPE_INTEGRATION_CONNECTED = 'integration_connected';
    const TYPE_SETTINGS_CHANGED    = 'settings_changed';
    const TYPE_LOGIN               = 'login';
    const TYPE_NOTE_CREATED        = 'note_created';
    const TYPE_NOTE_DELETED        = 'note_deleted';
    const TYPE_TASK_CREATED        = 'task_created';
    const TYPE_TASK_COMPLETED      = 'task_completed';
    const TYPE_TASK_DELETED        = 'task_deleted';

    protected $fillable = [
        'user_id',
        'type',
        'title',
        'description',
        'subject_type',
        'subject_id',
        'meta',
    ];

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

    protected static function boot(): void
    {
        parent::boot();

        static::creating(function ($model) {
            if (!$model->id) {
                $model->id = (string) Str::uuid();
            }
        });
    }

    // ── Relations ─────────────────────────────────────────────────────────

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

    public function subject()
    {
        return $this->morphTo();
    }

    // ── Scopes ────────────────────────────────────────────────────────────

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

    public function scopeSearch(Builder $query, string $term): Builder
    {
        return $query->where(function ($q) use ($term) {
            $q->where('title', 'like', "%{$term}%")
              ->orWhere('description', 'like', "%{$term}%");
        });
    }

    public function scopeOfType(Builder $query, string $type): Builder
    {
        // Gruppen-Alias auflösen
        $map = [
            'event'       => ['event_created', 'event_updated', 'event_deleted'],
            'reminder'    => ['reminder_sent'],
            'automation'  => ['automation_triggered'],
            'contact'     => ['contact_created', 'contact_updated'],
            'integration' => ['integration_connected'],
            'note'        => ['note_created', 'note_deleted'],
            'task'        => ['task_created', 'task_completed', 'task_deleted'],
            'system'      => ['settings_changed', 'login'],
        ];

        $types = $map[$type] ?? [$type];

        return $query->whereIn('type', $types);
    }

    // ── Helpers ───────────────────────────────────────────────────────────

    /** Liefert Icon-Name, Hintergrund- und Textfarbe für den Typ. */
    public function visual(): array
    {
        return match (true) {
            str_starts_with($this->type, 'event')       => ['icon' => 'calendar',                 'bg' => 'bg-indigo-50',  'text' => 'text-indigo-600'],
            str_starts_with($this->type, 'reminder')    => ['icon' => 'bell',                      'bg' => 'bg-amber-50',   'text' => 'text-amber-600'],
            str_starts_with($this->type, 'automation')  => ['icon' => 'bolt',                      'bg' => 'bg-purple-50',  'text' => 'text-purple-600'],
            str_starts_with($this->type, 'contact')     => ['icon' => 'user',                      'bg' => 'bg-green-50',   'text' => 'text-green-600'],
            str_starts_with($this->type, 'integration') => ['icon' => 'link',                      'bg' => 'bg-blue-50',    'text' => 'text-blue-600'],
            str_starts_with($this->type, 'note')        => ['icon' => 'document-text',             'bg' => 'bg-amber-50',   'text' => 'text-amber-600'],
            str_starts_with($this->type, 'task')        => ['icon' => 'check-circle',              'bg' => 'bg-teal-50',    'text' => 'text-teal-600'],
            $this->type === 'login'                     => ['icon' => 'arrow-right-on-rectangle',  'bg' => 'bg-gray-100',   'text' => 'text-gray-500'],
            default                                     => ['icon' => 'cog-6-tooth',               'bg' => 'bg-gray-100',   'text' => 'text-gray-500'],
        };
    }

    /** Menschlich lesbarer Typ-Label (lokalisiert). */
    public function typeLabel(): string
    {
        $locale = app()->getLocale();
        $labels = [
            'event_created'         => ['de' => 'Termin erstellt',         'en' => 'Event created'],
            'event_updated'         => ['de' => 'Termin bearbeitet',       'en' => 'Event updated'],
            'event_deleted'         => ['de' => 'Termin gelöscht',         'en' => 'Event deleted'],
            'reminder_sent'         => ['de' => 'Erinnerung gesendet',     'en' => 'Reminder sent'],
            'automation_triggered'  => ['de' => 'Automation ausgeführt',   'en' => 'Automation triggered'],
            'contact_created'       => ['de' => 'Kontakt erstellt',        'en' => 'Contact created'],
            'contact_updated'       => ['de' => 'Kontakt bearbeitet',      'en' => 'Contact updated'],
            'integration_connected' => ['de' => 'Integration verbunden',   'en' => 'Integration connected'],
            'settings_changed'      => ['de' => 'Einstellungen geändert',  'en' => 'Settings changed'],
            'login'                 => ['de' => 'Anmeldung',               'en' => 'Login'],
            'note_created'          => ['de' => 'Notiz erstellt',          'en' => 'Note created'],
            'note_deleted'          => ['de' => 'Notiz gelöscht',          'en' => 'Note deleted'],
            'task_created'          => ['de' => 'Aufgabe erstellt',        'en' => 'Task created'],
            'task_completed'        => ['de' => 'Aufgabe erledigt',        'en' => 'Task completed'],
            'task_deleted'          => ['de' => 'Aufgabe gelöscht',        'en' => 'Task deleted'],
        ];
        return $labels[$this->type][$locale] ?? $labels[$this->type]['de'] ?? $this->type;
    }

    /** Lokalisierter Aktivitäts-Titel für Activity::log()-Aufrufe. */
    public static function localizedTitle(string $key, string $locale = 'de'): string
    {
        $texts = [
            'task_created_assistant'   => ['de' => 'Aufgabe via Aria erstellt',  'en' => 'Task created via Aria'],
            'event_created_assistant'  => ['de' => 'Termin via Aria erstellt',   'en' => 'Event created via Aria'],
            'note_created_assistant'   => ['de' => 'Notiz via Aria erstellt',    'en' => 'Note created via Aria'],
            'contact_created_assistant'=> ['de' => 'Kontakt via Aria erstellt',  'en' => 'Contact created via Aria'],
            'task_created'             => ['de' => 'Aufgabe erstellt',           'en' => 'Task created'],
            'task_completed'           => ['de' => 'Aufgabe erledigt',           'en' => 'Task completed'],
            'task_deleted'             => ['de' => 'Aufgabe gelöscht',           'en' => 'Task deleted'],
            'event_created'            => ['de' => 'Termin erstellt',            'en' => 'Event created'],
            'event_updated'            => ['de' => 'Termin aktualisiert',        'en' => 'Event updated'],
            'event_deleted'            => ['de' => 'Termin gelöscht',            'en' => 'Event deleted'],
            'contact_created'          => ['de' => 'Kontakt erstellt',           'en' => 'Contact created'],
            'contact_updated'          => ['de' => 'Kontakt bearbeitet',         'en' => 'Contact updated'],
            'contact_deleted'          => ['de' => 'Kontakt gelöscht',           'en' => 'Contact deleted'],
            'note_created'             => ['de' => 'Notiz erstellt',             'en' => 'Note created'],
            'note_deleted'             => ['de' => 'Notiz gelöscht',             'en' => 'Note deleted'],
        ];
        return $texts[$key][$locale] ?? $texts[$key]['de'] ?? $key;
    }

    // ── Static Factory ────────────────────────────────────────────────────

    public static function log(
        string $userId,
        string $type,
        string $title,
        ?string $description = null,
        ?Model $subject = null,
        array $meta = []
    ): self {
        return self::create([
            'user_id'      => $userId,
            'type'         => $type,
            'title'        => $title,
            'description'  => $description,
            'subject_type' => $subject ? get_class($subject) : null,
            'subject_id'   => $subject?->id,
            'meta'         => $meta ?: null,
        ]);
    }
}
