<?php

namespace App\Console\Commands;

use App\Models\Client\Client;
use App\Models\Document\Document;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class ExportMissingClientDocuments extends Command
{
    protected $signature = 'documents:export-missing-client-files
                    {--disk=public}
                    {--output=missing-client-documents.csv}
                    {--start=}';

    protected $description = 'Export client documents that exist in DB but are missing from storage';

    public function handle(): int
    {
        $disk = $this->option('disk');
        $output = storage_path('app/' . $this->option('output'));

        $handle = fopen($output, 'w');

        fputcsv($handle, [
            'document_id',
            'client_id',
            'client_slug',
            'client_email',
            'client_name',
            'document_display_name',
            'document_type',
            'file_name',
            'uploaded_at',
            'expected_path',
        ]);

        $missingCount = 0;

        $query = Document::query()
                ->where('owner_type', Client::class)
                ->with(['owner', 'type'])
                ->orderBy('id');
            
            if ($start = $this->option('start')) {
                $query->whereDate('created_at', '>=', $start);
            }
            $query->chunkById(500, function ($documents) use ($disk, $handle, &$missingCount) {
                foreach ($documents as $document) {
                    $client = $document->owner;

                    if (!$client || !$client->slug || !$document->file_name) {
                        continue;
                    }

                    $expectedPath = 'clients/' . $client->slug . '/' . $document->file_name;

                    if (!Storage::disk($disk)->exists($expectedPath)) {
                        fputcsv($handle, [
                            $document->id,
                            $client->id,
                            $client->slug,
                            $client->email_address,
                            $client->fullName ?? trim(($client->name_first ?? '') . ' ' . ($client->name_last ?? '')),
                            $document->display_name,
                            $document->type?->display_name,
                            $document->file_name,
                            optional($document->created_at)?->format('Y-m-d H:i:s'),
                            'storage/app/public/' . $expectedPath,
                        ]);

                        $missingCount++;
                    }
                }
            });

        fclose($handle);

        $this->info("Export complete.");
        $this->info("Missing files found: {$missingCount}");
        $this->info("CSV saved to: {$output}");

        return self::SUCCESS;
    }
}