<?php
declare(strict_types=1);

namespace App\Services;

use App\Core\Auth;
use App\Core\Database;
use App\Models\Lead;
use App\Models\Opportunity;
use App\Models\User;

final class AutomationService
{
    public static function run(string $trigger, array $context = []): void
    {
        foreach (SetupService::automations($trigger) as $rule) {
            try {
                self::apply($rule, $context);
            } catch (\Throwable $e) {
                error_log('Automation failed: ' . $e->getMessage());
            }
        }
    }

    public static function syncOverdueTasks(): void
    {
        static $ran = false;
        if ($ran) {
            return;
        }
        $ran = true;
        if (SetupService::automations('task_overdue') === []) {
            return;
        }
        $tid = Auth::instance()->tenantId();
        if (!$tid) {
            return;
        }
        $rows = Database::instance()->fetchAll(
            "SELECT t.id, t.title, t.owner_id, CONCAT(u.first_name,' ',u.last_name) AS owner_name
             FROM tasks t
             LEFT JOIN users u ON u.id = t.owner_id
             WHERE t.tenant_id = :tid AND t.deleted_at IS NULL AND t.status = 'open'
               AND t.due_at IS NOT NULL AND DATE(t.due_at) < CURDATE()
             ORDER BY t.due_at ASC
             LIMIT 40",
            ['tid' => $tid]
        );
        foreach ($rows as $task) {
            self::run('task_overdue', [
                'task_id' => (int) $task['id'],
                'title' => (string) $task['title'],
                'owner_id' => (int) ($task['owner_id'] ?? 0),
                'owner_name' => trim((string) ($task['owner_name'] ?? '')),
                'related_type' => 'task',
                'related_id' => (int) $task['id'],
            ]);
        }
    }

    /** @param array<string, mixed> $rule */
    private static function apply(array $rule, array $ctx): void
    {
        $action = (string) ($rule['action'] ?? '');
        $title = trim((string) ($rule['title'] ?? 'Follow up')) ?: 'Follow up';
        $ownerId = (int) ($ctx['owner_id'] ?? 0);
        if ($action === 'create_task') {
            if (($ctx['related_type'] ?? '') === 'task') {
                return;
            }
            $dueDays = (int) ($rule['due_days'] ?? 1);
            RecordService::addTask([
                'title' => $title,
                'due_at' => date('Y-m-d 17:00:00', strtotime('+' . $dueDays . ' days')),
                'priority' => 'normal',
                'owner_id' => $ownerId ?: Auth::instance()->id(),
                'related_type' => $ctx['related_type'] ?? null,
                'related_id' => $ctx['related_id'] ?? null,
            ]);
            return;
        }
        if ($action === 'notify_owner' && $ownerId > 0) {
            $body = (string) ($ctx['title'] ?? $title);
            NotificationService::send($ownerId, $title, $body, self::urlFor($ctx));
            return;
        }
        if ($action === 'notify_manager') {
            $tid = Auth::instance()->tenantId();
            if (!$tid) {
                return;
            }
            $who = trim((string) ($ctx['owner_name'] ?? ''));
            $body = $who !== '' ? $who . ': ' . ($ctx['title'] ?? $title) : (string) ($ctx['title'] ?? $title);
            foreach (User::managers($tid) as $m) {
                $mid = (int) $m['id'];
                if ($mid === $ownerId) {
                    continue;
                }
                NotificationService::send($mid, $title, $body, self::urlFor($ctx));
            }
            return;
        }
        if ($action === 'assign_round_robin' && ($ctx['related_type'] ?? '') === 'lead' && !empty($ctx['related_id'])) {
            AssignmentService::assign((int) $ctx['related_id'], 'round_robin', null, null);
        }
    }

    /** @param array<string, mixed> $ctx */
    private static function urlFor(array $ctx): string
    {
        $type = (string) ($ctx['related_type'] ?? '');
        $id = (int) ($ctx['related_id'] ?? 0);
        return match ($type) {
            'lead' => $id ? '/leads/' . $id : '/leads',
            'opportunity' => $id ? '/opportunities/' . $id : '/opportunities',
            'account' => $id ? '/accounts/' . $id : '/accounts',
            'task' => $id ? '/tasks?n=' . $id : '/tasks',
            default => '/dashboard',
        };
    }
}
