<?php

namespace Database\Seeders;

use App\Models\Payment;
use App\Models\Plan;
use App\Models\Subscription;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;

class PaymentSeeder extends Seeder
{
    public function run(): void
    {
        $user = User::where('email', 'boban.blaskovic@gmail.com')->first();

        if (!$user) {
            $this->command->warn('Test-User nicht gefunden. Bitte zuerst DatabaseSeeder ausführen.');
            return;
        }

        // Bestehende Daten entfernen
        Payment::where('user_id', $user->id)->delete();
        Subscription::where('user_id', $user->id)->delete();

        // Pro-Plan ermitteln (höchster sort-Wert unter aktiven Plänen)
        $plan = Plan::where('active', true)->orderByDesc('sort')->first()
            ?? Plan::where('active', true)->first();

        if (!$plan) {
            $this->command->warn('Kein aktiver Plan gefunden. Bitte zuerst PlanSeeder ausführen.');
            return;
        }

        // Subscription erstellen (monatlich, seit 6 Monaten aktiv)
        $startsAt = now()->subMonths(6)->startOfMonth();
        $endsAt   = now()->addMonths(1)->startOfMonth();

        $subscription = Subscription::create([
            'user_id'                    => $user->id,
            'plan_id'                    => $plan->id,
            'plan_name'                  => $plan->name,
            'plan_slug'                  => $plan->plan_key ?? Str::slug($plan->name),
            'price'                      => $plan->price,
            'original_price'             => $plan->price,
            'discount_amount'            => null,
            'interval'                   => 'monthly',
            'status'                     => 'active',
            'starts_at'                  => $startsAt,
            'ends_at'                    => $endsAt,
            'provider'                   => 'stripe',
            'provider_customer_id'       => 'cus_demo' . Str::random(8),
            'provider_subscription_id'   => 'sub_demo' . Str::random(8),
        ]);

        // Zahlungen: 5 erfolgreiche monatliche + 1 fehlgeschlagene + 1 ausstehende
        $payments = [
            // Fehlgeschlagene Zahlung (vor 4 Monaten, dann erneut versucht)
            [
                'months_ago' => 4,
                'status'     => 'failed',
                'paid_at'    => null,
            ],
            // Erfolgreiche Zahlungen (monatlich)
            ['months_ago' => 5, 'status' => 'paid'],
            ['months_ago' => 4, 'status' => 'paid'], // Wiederholung nach Failed
            ['months_ago' => 3, 'status' => 'paid'],
            ['months_ago' => 2, 'status' => 'paid'],
            ['months_ago' => 1, 'status' => 'paid'],
            // Aktuelle Periode: ausstehend
            [
                'months_ago' => 0,
                'status'     => 'pending',
                'paid_at'    => null,
            ],
        ];

        foreach ($payments as $p) {
            $date = now()->subMonths($p['months_ago'])->startOfMonth();

            Payment::create([
                'user_id'            => $user->id,
                'subscription_id'    => $subscription->id,
                'amount'             => $plan->price,
                'currency'           => 'EUR',
                'status'             => $p['status'],
                'provider'           => 'stripe',
                'provider_payment_id' => 'pi_demo' . Str::random(12),
                'paid_at'            => $p['status'] === 'paid' ? $date : ($p['paid_at'] ?? null),
                'created_at'         => $date,
                'updated_at'         => $date,
            ]);
        }

        $this->command->info("Subscription + {$subscription->plan_name}-Plan + " . count($payments) . " Zahlungen für {$user->email} erstellt.");
    }
}
