<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Mtc\Shop\Assessment\Answer;
use Mtc\Shop\Assessment\Assessment;

class CleanupDraftAssessments extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'assessments:cleanup-drafts
                            {--all : Delete all drafts regardless of expiry}
                            {--member= : Only delete drafts for a specific member ID}
                            {--form= : Only delete drafts for a specific form ID}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Delete expired draft assessments and their answers';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $query = Assessment::query()
            ->where('is_completed', 0);

        if (!$this->option('all')) {
            $expiryDays = Assessment::getDraftExpiryDays();
            $query->where('updated_at', '<', Carbon::now()->subDays($expiryDays));
            $this->info("Finding drafts older than {$expiryDays} days...");
        } else {
            $this->info('Finding all draft assessments...');
        }

        if ($memberId = $this->option('member')) {
            $query->where('member_id', $memberId);
            $this->info("Filtering to member ID: {$memberId}");
        }

        if ($formId = $this->option('form')) {
            $query->where('form_id', $formId);
            $this->info("Filtering to form ID: {$formId}");
        }

        $draftIds = $query->pluck('id');

        if ($draftIds->isEmpty()) {
            $this->info('No matching draft assessments found.');
            return 0;
        }

        $this->info("Found {$draftIds->count()} draft(s) to delete.");

        if (!$this->option('all') || $this->confirm('Proceed with deletion?')) {
            $answersDeleted = Answer::whereIn('assessment_id', $draftIds)->delete();
            $draftsDeleted = Assessment::whereIn('id', $draftIds)->delete();

            $this->info("Deleted {$draftsDeleted} draft(s) and {$answersDeleted} answer(s).");
        }

        return 0;
    }
}
