<?php

namespace App\Console\Commands;

use App\Models\TobescrappedCandidate;
use Carbon\Carbon;
use Illuminate\Console\Command;

class CreateToBeScrapedCandidatesUrlFile extends Command
{
    /** /toBeScrapedCandidatesUrlFile
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'create-to-be-scraped-candidates-url-file';

    protected $octaparseApiService;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'push the new candidate urls to octaparse task for scrapping the source code';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $candidates = $this->getCandidates();
        if($candidates->isEmpty()) {
            info('No candidates to be scrapped');
            return;
        }
        $data = '';
        $ids = [];
        foreach ($candidates as $candidate) {
            $data .= $candidate->url. PHP_EOL;
            $ids[] = $candidate->id;
        }
        if($data !='') {
            $randomNumber = rand(10000, 99999);
            $fileName = 'toBeScrapped_' .$randomNumber. now()->timestamp . '.txt';
            $filePath = storage_path('app/public/scraper/' . $fileName);
            if (!file_exists(storage_path('app/public/scraper'))) {
                mkdir(storage_path('app/public/scraper'), 0777, true);
            }
            file_put_contents($filePath, $data);
            $this->updateCandidatesUrlPool($ids);
        }
    }

    private function getCandidates()
    {
        $candidates = [];
        $candidates = TobescrappedCandidate::where('status',1)
                                ->orWhere(function ($subQuery) {
                                    $subQuery->where('status', 0)
                                            ->where('picked_at', '<', Carbon::now()->subDay());
                                })
                                ->inRandomOrder()->take(200)->get();
        return $candidates;
    }

    private function updateCandidatesUrlPool($ids)
    {
        TobescrappedCandidate::whereIn('id', $ids)->update([
            'status' => 0,
            'picked_at' => Carbon::now()
        ]);
    }
}
