<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreWebsiteRequest;
use App\Http\Requests\UpdateWebsiteRequest;
use App\Models\Website;
use App\Repositories\WebsiteRepository;
use App\Services\AuditLogService;
use App\Services\BackupService;
use App\Services\WebsiteService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class WebsiteController extends Controller
{
    public function __construct(
        protected WebsiteRepository $websites,
        protected WebsiteService $websiteService,
    ) {
    }

    public function index(Request $request): View
    {
        $this->authorize('viewAny', Website::class);

        return view('websites.index', [
            'filters' => $request->only('search', 'status'),
            'websites' => $this->websites->paginateForIndex($request->only('search', 'status')),
        ]);
    }

    public function create(): View
    {
        $this->authorize('create', Website::class);

        return view('websites.create');
    }

    public function store(StoreWebsiteRequest $request): RedirectResponse
    {
        $website = $this->websiteService->create($request->validated(), $request->user());
        $website = $website->fresh(['agent', 'siteHealthLogs']);
        $verified = $website->agent?->authentication_status === 'verified';
        $message = $verified
            ? 'Website added, connection tested, and agent verified successfully.'
            : 'Website added, but the first connection test did not fully verify the agent.';

        return redirect()
            ->route('websites.show', $website)
            ->with($verified ? 'status' : 'error', $message);
    }

    public function show(Website $website, Request $request): View
    {
        $this->authorize('view', $website);
        $website = $this->websites->findForDetail($website);
        $activeTab = $request->string('tab')->toString() ?: 'overview';

        return view('websites.show', [
            'website' => $website,
            'activeTab' => $activeTab,
            'tableSnapshots' => $activeTab === 'database'
                ? $website->tableSnapshots()->orderBy('table_name')->paginate(10, ['*'], 'tables_page')
                : null,
            'backups' => $activeTab === 'backups'
                ? $website->backups()->with('initiatedBy')->latest()->paginate(8, ['*'], 'backups_page')
                : null,
            'activityLogs' => $activeTab === 'logs'
                ? $website->activityLogs()->with('user')->latest('occurred_at')->paginate(10, ['*'], 'logs_page')
                : null,
            'recentBackup' => $website->backups()->latest('created_at')->first(),
            'recentLogs' => $website->activityLogs()->with('user')->latest('occurred_at')->limit(5)->get(),
        ]);
    }

    public function edit(Website $website): View
    {
        $this->authorize('update', $website);

        return view('websites.edit', ['website' => $website]);
    }

    public function update(UpdateWebsiteRequest $request, Website $website): RedirectResponse
    {
        $this->authorize('update', $website);
        $website = $this->websiteService->update($website, $request->validated(), $request->user());

        return redirect()
            ->route('websites.show', $website)
            ->with('status', 'Website connection details updated.');
    }

    public function sync(Website $website, Request $request): RedirectResponse
    {
        $this->authorize('update', $website);
        $result = $this->websiteService->sync($website, $request->user());

        return back()->with($result['ok'] ? 'status' : 'error', $result['message']);
    }

    public function toggleStatus(Website $website, Request $request): RedirectResponse
    {
        $this->authorize('update', $website);
        $website = $this->websiteService->toggleStatus($website, $request->user());

        return back()->with('status', "Website is now {$website->status}.");
    }

    public function destroy(Website $website, Request $request, AuditLogService $auditLog): RedirectResponse
    {
        $this->authorize('delete', $website);

        $name = $website->name;
        $website->delete();

        $auditLog->record('website', 'website.deleted', "Website {$name} was removed from the control center.", null, $request->user());

        return redirect()->route('websites.index')->with('status', 'Website deleted.');
    }
}
