<?php

namespace App\Console\Commands;

use App\Helpers\HashesHelpers;
use App\Models\EntryHash;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;

#[Signature('hashes:calculate')]
#[Description('Recalculate all hashes for EntryHashes')]
class CalculateAllHashes extends Command
{
    public function handle()
    {
        EntryHash::where('verified', '=', 'TBD')->cursor()->each(function ($entryHash) {
            if( ( $hash = HashesHelpers::findHashes( $entryHash->hash_sha1 ) ) !== null ){
                $entryHash->filename = $hash->filename;
                $entryHash->hash_crc32 = $hash->crc32;
                $entryHash->hash_sha1 = $hash->sha1;
                $entryHash->verified = HashesHelpers::getReferenceName( $hash->dat_reference_id );
                $entryHash->save();
            } else {
                if( !$entryHash->hash_crc32 || !$entryHash->hash_sha1 )
                    $entryHash->delete();
                else {
                    if (!$entryHash->filename)
                        $entryHash->filename = "Unknown";
                    $entryHash->verified = 'No';
                    $entryHash->save();
                }
            }
        });

        $this->info('Hashes calculated');
    }
}
