<?php

namespace App\Services;

use App\Models\Business;
use App\Models\Loan;
use App\Models\Task;
use Carbon\CarbonImmutable;

class TaskAutomationService
{
    public function __construct(private ManagementWorkSettings $settings) {}

    public function process(string|CarbonImmutable|null $date = null): array
    {
        $asOf = $date instanceof CarbonImmutable ? $date : CarbonImmutable::parse($date ?: now());
        $created = 0;
        $skipped = 0;

        foreach (Business::query()->with('branches')->get() as $business) {
            $config = $this->settings->values($business);
            if (! $config['collection_tasks_enabled']) {
                continue;
            }

            $branchIds = $business->branches->pluck('id');
            $loans = Loan::query()->with(['branch','customer','creator'])
                ->whereIn('branch_id', $branchIds)
                ->where('status', 'active')
                ->where('days_overdue', '>=', $config['collection_task_overdue_days'])
                ->orderByDesc('days_overdue')->get();

            foreach ($loans as $loan) {
                $openExists = Task::query()
                    ->where('category', 'collection')
                    ->where('source_type', Loan::class)
                    ->where('source_id', $loan->id)
                    ->whereIn('status', ['pending','in_progress'])
                    ->exists();
                if ($openExists) {
                    $skipped++;
                    continue;
                }

                $automationKey = 'collection:loan:'.$loan->id.':'.$asOf->toDateString();
                if (Task::query()->where('automation_key', $automationKey)->exists()) {
                    $skipped++;
                    continue;
                }

                $assignee = $loan->creator && $loan->creator->status === 'active'
                    ? $loan->creator->id
                    : $loan->branch?->manager_user_id;

                Task::create([
                    'branch_id' => $loan->branch_id,
                    'title' => 'Collect overdue loan '.$loan->loan_number,
                    'description' => trim(($loan->customer?->full_name ?: 'Customer').' is '.$loan->days_overdue.' day(s) overdue. Current overdue amount: '.$loan->total_overdue.'.'),
                    'category' => 'collection',
                    'priority' => $loan->days_overdue >= 30 ? 'high' : 'normal',
                    'status' => 'pending',
                    'due_at' => $asOf->startOfDay()->setTime(9, 0),
                    'assigned_to' => $assignee,
                    'source_type' => Loan::class,
                    'source_id' => $loan->id,
                    'automation_key' => $automationKey,
                ]);
                $created++;
            }
        }

        return ['created' => $created, 'skipped' => $skipped];
    }
}