<?php

namespace App\Console;

use App\TwitchWebhook;
use Carbon\Carbon;
use App\Http\Controllers\WebhookController;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use romanzipp\Twitch\Facades\Twitch;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // resubscribe to nearly expired hooks (1 hour after expire)
        $schedule->call(function () {
            $hooks = TwitchWebhook::where("disabled", false)->where("disabled_at", null)->whereDate("expires_at", "<=", Carbon::now()->addHour())->get();

            foreach ($hooks as $hook) {
                $subscription = Twitch::subscribeWebhook($hook->callback, $hook->topic, WebhookController::MAX_LEASE_SECONDS);

                if ($subscription->success) {
                    $hook->expires_at = Carbon::now()->addSeconds(WebhookController::MAX_LEASE_SECONDS);
                    $hook->save();

                } else {
                    // TODO: handle error
                }
            }

        })->everyThirtyMinutes();

        // unsubscribe from disabled hooks (disabled 1 day ago)
        $schedule->call(function () {
            $hooks = TwitchWebhook::where("disabled", false)->whereDate("disabled_at", "<=", Carbon::now()->subDay())->get();

            foreach ($hooks as $hook) {
                $unsubscription = Twitch::unsubscribeWebhook($hook->callback, $hook->topic);

                if ($unsubscription->success) {
                    $hook->disabled = true;
                    $hook->save();

                } else {
                    // TODO: handle error
                }

            }
        })->everyThirtyMinutes();

    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}
