<?php

namespace App\Filament\Resources\LoyaltyProgramResource\Pages;

use App\Filament\Resources\LoyaltyProgramResource;
use App\Models\Loyalty\LoyaltyProgram;
use App\Services\AuditLog;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\DB;

/**
 * Ported from LoyaltyProgramController::store() — program plus its tiers
 * created inside one transaction, then the audit entry.
 */
class CreateLoyaltyProgram extends CreateRecord
{
    protected static string $resource = LoyaltyProgramResource::class;

    protected function handleRecordCreation(array $data): LoyaltyProgram
    {
        return DB::transaction(function () use ($data): LoyaltyProgram {
            $program = LoyaltyProgram::create([
                'name' => $data['name'],
                'base_earn_rate' => $data['base_earn_rate'],
                'redemption_rate' => $data['redemption_rate'],
                'minimum_purchase_to_earn' => $data['minimum_purchase_to_earn'] ?? 0,
                'minimum_points_to_redeem' => $data['minimum_points_to_redeem'] ?? 0,
                'points_validity_days' => $data['points_validity_days'] ?? null,
                'is_active' => $data['is_active'] ?? true,
            ]);

            foreach ($data['tiers'] ?? [] as $tier) {
                $program->tiers()->create([
                    'name' => $tier['name'],
                    'code' => $tier['code'],
                    'min_lifetime_points' => $tier['min_lifetime_points'],
                    'earn_multiplier' => $tier['earn_multiplier'] ?? 1,
                    'color' => $tier['color'] ?? null,
                ]);
            }

            AuditLog::record('loyalty_program.created', $program, ['name' => $program->name]);

            return $program;
        });
    }

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