<?php

namespace App\Filament\Resources\VoucherResource\Pages;

use App\Filament\Resources\VoucherResource;
use App\Models\Lookups\VoucherType;
use App\Models\Vouchers\Voucher;
use App\Services\VoucherService;
use Filament\Resources\Pages\CreateRecord;

/**
 * Ported from VoucherController::store(). VoucherService::generate() owns code
 * generation and the opening status; the balance fields are only populated for
 * balance-based voucher types, and an operator-supplied code overwrites the
 * generated one afterwards — all exactly as the source does it.
 */
class CreateVoucher extends CreateRecord
{
    protected static string $resource = VoucherResource::class;

    protected function handleRecordCreation(array $data): Voucher
    {
        if (filled($data['branch_id'] ?? null)) {
            VoucherResource::assertBranchAccessible((int) $data['branch_id']);
        }

        $voucherType = VoucherType::findOrFail($data['voucher_type_id']);

        // DELIBERATE DEVIATION — see Decisions Log #44. The source controller
        // passes `'code' => $data['code'] ?? null` into generate(), which does
        // `Voucher::create($attributes + ['code' => $generated])`. PHP's `+`
        // keeps the LEFT operand, so that null wins and the generated code is
        // discarded — and `vouchers.code` is NOT NULL, so leaving the code blank
        // crashes with a database error in the live source app. The key is
        // therefore omitted entirely when blank, which lets generate() do the
        // auto-generation its own docblock (and the controller's "Honor an
        // operator-chosen code over the auto-generated one" comment) intends.
        // No service code was changed.
        $attributes = [
            'name' => $data['name'],
            'voucher_type_id' => $data['voucher_type_id'],
            'discount_type_id' => $data['discount_type_id'] ?? null,
            'discount_value' => $data['discount_value'] ?? 0,
            'initial_balance' => $voucherType->is_balance_based ? ($data['initial_balance'] ?? 0) : null,
            'remaining_balance' => $voucherType->is_balance_based ? ($data['initial_balance'] ?? 0) : null,
            'minimum_purchase' => $data['minimum_purchase'] ?? 0,
            'maximum_discount' => $data['maximum_discount'] ?? null,
            'usage_limit' => $data['usage_limit'] ?? null,
            'is_partial_redemption' => $data['is_partial_redemption'] ?? false,
            'is_stackable' => $data['is_stackable'] ?? false,
            'is_active' => $data['is_active'] ?? true,
            'customer_id' => $data['customer_id'] ?? null,
            'branch_id' => $data['branch_id'] ?? null,
            'valid_from' => $data['valid_from'] ?? null,
            'valid_until' => $data['valid_until'] ?? null,
            'notes' => $data['notes'] ?? null,
        ];

        if (! empty($data['code'])) {
            $attributes['code'] = $data['code'];
        }

        $voucher = app(VoucherService::class)->generate($attributes);

        // Honor an operator-chosen code over the auto-generated one.
        if (! empty($data['code'])) {
            $voucher->update(['code' => $data['code']]);
        }

        return $voucher;
    }

    protected function getRedirectUrl(): string
    {
        return VoucherResource::getUrl('index');
    }
}
