<?php

namespace App\Console\Commands;

use App\Helpers\EntryHelpers;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Spatie\SimpleExcel\SimpleExcelReader;

#[Signature('migrate:files:execute {--csv-file=} {--favorite-server=oedipus} ')]
#[Description("Migrate all files tables into an EntryFile.")]
class MigrateFilesExecute extends Command
{

    private function getState( array $file ): string
    {
        if( str_contains( $file['old_path'], 'private' ) )
            return 'private';
        if( str_contains( $file['old_path'], 'archive' ) )
            return 'archived';
        return 'public';
    }

    private function getNewPath( array $file ): string
    {
        $newPath = $file['new_path'];
        $newPath = str_replace('rhpz-fs-storage//', '', $newPath);
        $newPath = str_replace( './rhpz-fs-storage/', '', $newPath);

        return dirname($newPath);
    }

    private function createEntryFile( array $file )
    {
        $exists = DB::table('migration_files')
            ->where('filename', $file['filename'] )
            ->where('old_path', $file['old_path'] )
            ->where('wp_post_id', (int) $file['wp_post_id'] )
            ->where('uuid', $file['uuid'] )
            ->where('new_path', $this->getNewPath( $file ) )
            ->exists();

        if( $exists )
            return;

        $entryId = DB::table('migrations_logs')
            ->where('source_system', 'wp')
            ->where('source_table', 'wp_posts')
            ->where('target_table', 'entries' )
            ->where('source_id', (int) $file['wp_post_id'] )
            ->value('target_id');

        if( !$entryId ){
            $this->info("Not copied entry for {$file['wp_post_id']}");
            return;
        }

        $fileId = DB::table('entry_files')->insertGetId([
            'entry_id' => $entryId,
            'filename' => $file['filename'],
            'filepath' => $this->getNewPath( $file ),
            'favorite_server' => $this->option('favorite-server') ?? "oedipus",
            'favorite_at' => now(),
            'filesize' => (int) $file['filesize'],
            'created_at' => now(),
            'updated_at' => now(),
            'file_uuid' => $file['uuid'],
            'state' => $this->getState( $file ),
            'online_patcher' => (int) EntryHelpers::enableOnlinePatcherBasedOnExtension( $file['filename'] ),
            'secondary_online_patcher' => 0,
            'download_count' => 0
        ]);

        if( !$fileId ){
            $this->info( "Not created file for {$file['wp_post_id']}" );
            return;
        }

        DB::table('migration_files')->insert([
            'filename' => $file['filename'],
            'old_path' => $file['old_path'],
            'wp_post_id' => (int) $file['wp_post_id'],
            'uuid' => $file['uuid'],
            'new_path' => $this->getNewPath( $file ),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $this->info( "Created file for {$file['wp_post_id']}" );

    }

    public function handle()
    {
        $csvFile = $this->option('csv-file');
        if( !$csvFile || !is_file($csvFile) ){
            $this->error('Missing CSV file Path');
            return self::FAILURE;
        }

        $rows = SimpleExcelReader::create($csvFile)->useDelimiter(';')->getRows();
        $rows->each(function(array $row){
            $this->createEntryFile($row);
        });

        return self::SUCCESS;
    }
}
