<?php

namespace App\Http\Resources;

use Carbon\Carbon;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\Form;
use Mtc\MercuryDataModels\FormActivity;

class FormList extends \Mtc\Crm\Http\Resources\FormList
{
    private array $activityData = [];

    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     * @return array
     */
    public function toArray($request)
    {
        $this->loadActivityData();

        if ($this->resource instanceof LengthAwarePaginator) {
            $resource = $this->resource
                ->through(fn(Form $form) => $this->mapRecord($form))
                ->toArray();

            $resource['default_columns'] = [
                'updated',
                'type',
            ];
            return $resource;
        }

        return $this->resource
            ->map(fn(Form $form) => $this->mapRecord($form))
            ->toArray();
    }

    private function loadActivityData(): void
    {
        $today = Carbon::now()->toDateString();
        $weekAgo = Carbon::now()->subDays(7)->toDateString();

        $todayStats = FormActivity::query()
            ->where('date', $today)
            ->get()
            ->keyBy('form_id');

        $weekStats = FormActivity::query()
            ->where('date', '>=', $weekAgo)
            ->get()
            ->groupBy('form_id')
            ->map(function ($activities) {
                return [
                    'total_submissions' => $activities->sum('total_submissions'),
                    'success_count' => $activities->sum('success_count'),
                    'validation_error_count' => $activities->sum('validation_error_count'),
                    'failure_count' => $activities->sum('failure_count'),
                ];
            });

        $formIds = $todayStats->keys()->merge($weekStats->keys())->unique();

        $this->activityData = $formIds->mapWithKeys(function ($formId) use ($todayStats, $weekStats) {
            $todayData = $todayStats->get($formId);
            $weekData = $weekStats->get($formId, [
                'total_submissions' => 0,
                'success_count' => 0,
                'validation_error_count' => 0,
                'failure_count' => 0,
            ]);

            return [
                $formId => [
                    'today' => [
                        'total' => $todayData?->total_submissions ?? 0,
                        'success' => $todayData?->success_count ?? 0,
                        'validation_error' => $todayData?->validation_error_count ?? 0,
                        'failure' => $todayData?->failure_count ?? 0,
                    ],
                    'week' => [
                        'total' => $weekData['total_submissions'],
                        'success' => $weekData['success_count'],
                        'validation_error' => $weekData['validation_error_count'],
                        'failure' => $weekData['failure_count'],
                    ],
                ],
            ];
        })->toArray();
    }

    public function mapRecord(Form $form)
    {
        return [
            'id' => $form->id,
            'name' => $form->name,
            'title' => $form->name,
            'active' => (bool)$form->is_active,
            'link' => '/crm/forms/edit/' . $form->id,
            'metaItems' => [
                'updated' => $form->updated_at->diffForHumans(),
                'type' => $form->type?->name,
            ],
            'activity' => $this->activityData[$form->id] ?? null,
        ];
    }
}
