<?php

namespace App\Http\Controllers;

use App\Http\Requests\ArchiveSettingRequest;
use App\Models\Action;
use App\Models\ArchiveEntity;
use App\Models\ArchiveSetting;
use App\Models\Segment;
use App\Services\Archiving\ArchiveExecutor;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class ArchiveSettingController extends Controller
{
    public function index(Request $request): Response
    {
        $settings = ArchiveSetting::query()
            ->latest()
            ->paginate(25)
            ->withQueryString();

        $archiveEntities = ArchiveEntity::query()
            ->where('enabled', true)
            ->orderBy('focus')
            ->get(['id', 'focus', 'name', 'related']);

        return Inertia::render('Settings/Archive/Index', [
            'settings' => $settings,
            'archiveEntities' => $archiveEntities,
            'actions' => Action::query()->with('decisions:id,name')->orderBy('name')->get(['id', 'name', 'segment_id']),
            'segments' => Segment::query()->orderBy('name')->get(['id', 'name']),
            'chainPatterns' => config('archiving.chains'),
        ]);
    }

    public function store(ArchiveSettingRequest $request): RedirectResponse
    {
        $data = $request->validated();
        $data['created_by'] = $request->user()?->id;
        ArchiveSetting::create($data);

        return redirect()->back()->with('flash.banner', 'Archive rule created');
    }

    public function update(ArchiveSettingRequest $request, ArchiveSetting $archiveSetting): RedirectResponse
    {
        $data = $request->validated();
        $data['updated_by'] = $request->user()?->id;
        $archiveSetting->update($data);

        return redirect()->back()->with('flash.banner', 'Archive rule updated');
    }

    public function destroy(ArchiveSetting $archiveSetting): RedirectResponse
    {
        $archiveSetting->delete();

        return redirect()->back()->with('flash.banner', 'Archive rule deleted');
    }

    public function run(ArchiveSetting $archiveSetting, Request $request): RedirectResponse
    {
        // Allow manual triggering even if strategy is manual or disabled? We'll require enabled.
        if (! $archiveSetting->enabled) {
            return back()->with('flash.banner', 'Rule is disabled');
        }
        $executor = app(ArchiveExecutor::class);
        $results = $executor->executeSetting($archiveSetting, context: null, userId: $request->user()?->id);
        $summary = empty($results) ? 'No rows matched.' : collect($results)->map(fn ($c, $t) => "$t:$c")->implode(', ');

        return back()->with('flash.banner', 'Archive run complete: '.$summary);
    }
}
