<?php

namespace App\Services\Draw;

use App\Models\Draw;
use App\Models\TicketOrder;
use App\Lottery\DrawStatus;
use Illuminate\Support\Facades\DB;

/**
 * 物理删除误建的未开始期号（无注单、无开奖结果）。
 */
final class DrawDestroyService
{
    public function destroy(Draw $draw): void
    {
        DB::transaction(function () use ($draw): void {
            /** @var Draw $locked */
            $locked = Draw::query()->whereKey($draw->id)->lockForUpdate()->firstOrFail();

            if ($locked->status !== DrawStatus::Pending->value) {
                throw new \RuntimeException('draw_not_deletable');
            }

            if ($locked->resultBatches()->exists()) {
                throw new \RuntimeException('draw_result_exists');
            }

            $betTotal = (int) TicketOrder::query()->where('draw_id', $locked->id)->sum('total_actual_deduct');
            if ($betTotal > 0) {
                throw new \RuntimeException('draw_has_bets');
            }

            $locked->delete();
        });
    }
}
