<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use App\Models\LicenseDomain;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class SyncDomainMonitors extends Command
{
    protected $signature = 'monitor:sync-domain {domain_id}';
    protected $description = 'Sync selected domain into monitors table';

    public function handle()
    {
        $domainId = $this->argument('domain_id');

        $domain = LicenseDomain::find($domainId);

        if (! $domain) {
            $this->error('Selected domain not found.');
            return Command::FAILURE;
        }

        $exists = DB::table('monitors')
            ->where('url', $domain->domain)
            ->exists();

        if ($exists) {
            $this->warn("Already monitored: {$domain->domain}");
            return Command::SUCCESS;
        }

        DB::table('monitors')->insert([
            'url'                              => $domain->domain,
            'uptime_check_enabled'             => 1,
            'uptime_check_interval_in_minutes' => 5,
            'uptime_status'                    => 'not_yet_checked',
            'uptime_check_method'              => 'GET',
            'certificate_check_enabled'        => 0,
            'created_at'                       => Carbon::now(),
            'updated_at'                       => Carbon::now(),
        ]);

        $this->info("Domain synced successfully: {$domain->domain}");

        return Command::SUCCESS;
    }
}
