<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class ClearMachineStatuses extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:clear-machine-statuses';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '備份並清空 machine_statuses 表，每週保留一次';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $day = now()->format('l'); // e.g. "Monday"
        $targetTable = "machine_statuses_" . $day;

        DB::statement("CREATE TABLE IF NOT EXISTS _machine_statuses LIKE machine_statuses");

        // 先刪除舊表（如存在）
        DB::statement("DROP TABLE IF EXISTS {$targetTable}");

        // 改名備份
        DB::statement("RENAME TABLE machine_statuses TO {$targetTable}");

        // 空表回命名
        DB::statement("RENAME TABLE _machine_statuses TO machine_statuses");

        $this->info("Machine statuses backed up to {$targetTable} and table cleared.");
    }
}
