<?php

namespace App\Services;

use App\Models\User;
use App\Models\Website;
use App\Repositories\WebsiteRepository;

class WebsiteService
{
    public function __construct(
        protected WebsiteRepository $websites,
        protected AuditLogService $auditLog,
        protected RemoteAgentService $remoteAgent,
    ) {
    }

    public function create(array $data, User $user): Website
    {
        $website = $this->websites->create([
            ...$data,
            'created_by' => $user->id,
            'status' => 'pending',
        ]);

        $website->agent()->create([
            'status' => 'pending',
            'authentication_status' => 'pending',
            'sync_status' => 'pending',
            'capabilities' => ['health', 'tables', 'table-structure', 'backups'],
        ]);

        $this->auditLog->record('website', 'website.created', "Website {$website->name} was added to the control center.", $website, $user);

        $syncResult = $this->remoteAgent->synchronize($website);

        $this->auditLog->record(
            'agent',
            $syncResult['ok'] ? 'agent.verified_on_create' : 'agent.verification_failed_on_create',
            $syncResult['message'],
            $website,
            $user
        );

        return $website->fresh('agent');
    }

    public function update(Website $website, array $data, User $user): Website
    {
        $updatedWebsite = $this->websites->update($website, $data);

        $this->auditLog->record('website', 'website.updated', "Website {$updatedWebsite->name} settings were updated.", $updatedWebsite, $user);

        return $updatedWebsite;
    }

    public function toggleStatus(Website $website, User $user): Website
    {
        $nextStatus = $website->status === 'disabled' ? 'pending' : 'disabled';

        $website->update([
            'status' => $nextStatus,
            'health_status' => $nextStatus === 'disabled' ? 'unknown' : $website->health_status,
        ]);

        $website->agent?->update([
            'status' => $nextStatus === 'disabled' ? 'offline' : 'pending',
            'sync_status' => $nextStatus === 'disabled' ? 'stale' : 'pending',
        ]);

        $this->auditLog->record('website', 'website.toggled', "Website {$website->name} was switched to {$nextStatus}.", $website, $user);

        return $website->fresh('agent');
    }

    public function sync(Website $website, User $user): array
    {
        $result = $this->remoteAgent->synchronize($website);

        $this->auditLog->record(
            'agent',
            $result['ok'] ? 'agent.sync_succeeded' : 'agent.sync_failed',
            $result['message'],
            $website,
            $user
        );

        return $result;
    }
}
