<?php

namespace MtcPharmacy\Subscriptions\Console\Commands;

use Carbon\Carbon;
use Mtc\Shop\Item as ShopItem;
use Mtc\Shop\Item\Size as ShopItemSize;
use Illuminate\Console\Command;
use Mtc\Modules\Members\Models\Member;
use MtcPharmacy\Subscriptions\Classes\Subscription;
use MtcPharmacy\Subscriptions\Classes\SubscriptionItem;
use MtcPharmacy\Subscriptions\Classes\SubscriptionPreference;

/**
 * Create a test subscription for manual testing
 *
 * Usage:
 *     php artisan subscriptions:setup-test
 *     php artisan subscriptions:setup-test --member-id=123
 *     php artisan subscriptions:setup-test --status=active --interval=weeks
 */
class SetupTestSubscriptionCommand extends Command
{
    protected $signature = 'subscriptions:setup-test
                            {--member-id= : Specific member ID to use}
                            {--status=pending : Subscription status (pending, active, paused)}
                            {--interval=months : Interval type (days, weeks, months)}
                            {--multiplier=1 : Interval multiplier}
                            {--items=1 : Number of items to add}';

    protected $description = 'Create a test subscription with sample data for manual testing';

    public function handle()
    {
        $this->info('🧪 Setting up test subscription...');
        $this->newLine();

        // Get or create member
        $member = $this->getMember();
        if (!$member) {
            $this->error('No members found in database. Please create a member first.');
            return 1;
        }

        $this->info("✓ Using member: {$member->full_name} (ID: {$member->id})");

        // Get shop items
        $shopItems = ShopItem::active()->with('sizes')->take($this->option('items'))->get();
        if ($shopItems->isEmpty()) {
            $this->error('No active shop items found. Please add products first.');
            return 1;
        }

        // Create subscription
        $subscription = new Subscription();
        $subscription->member_id = $member->id;
        $subscription->status = $this->option('status');
        $subscription->interval = $this->option('interval');
        $subscription->interval_multiplier = (int) $this->option('multiplier');
        $subscription->can_be_paused = true;
        $subscription->max_number_of_issues = 12;
        $subscription->expiry_date = now()->addYear()->format('Y-m-d');
        $subscription->next_issue_date = now()->addDays(7)->format('Y-m-d');
        $subscription->save();

        $this->info("✓ Created subscription (ID: {$subscription->id})");

        // Add items to subscription
        $totalPrice = 0;
        foreach ($shopItems as $shopItem) {
            $subscriptionItem = new SubscriptionItem();
            $subscriptionItem->subscription_id = $subscription->id;
            $subscriptionItem->shop_item_id = $shopItem->id;

            // Add size if available
            if ($shopItem->sizes->isNotEmpty()) {
                $size = $shopItem->sizes->first();
                $subscriptionItem->shop_item_size_id = $size->id;
                $totalPrice += $size->price;
                $displayName = "{$shopItem->name} ({$size->strength} x {$size->size})";
            } else {
                $totalPrice += $shopItem->price;
                $displayName = $shopItem->name;
            }

            $subscriptionItem->save();
            $this->info("  ✓ Added item: {$displayName}");
        }

        $subscription->price_per_issue = $totalPrice;
        $subscription->save();

        // Summary
        $this->newLine();
        $this->info('🎉 Test subscription created successfully!');
        $this->newLine();
        $this->table(
            ['Property', 'Value'],
            [
                ['Subscription ID', $subscription->id],
                ['Member', "{$member->full_name} ({$member->email})"],
                ['Status', $subscription->status],
                ['Interval', "{$subscription->interval_multiplier} {$subscription->interval}"],
                ['Items', $subscription->items->count()],
                ['Price per Issue', '£' . number_format($subscription->price_per_issue, 2)],
                ['Next Issue Date', $subscription->next_issue_date],
                ['Expiry Date', $subscription->expiry_date],
                ['Max Issues', $subscription->max_number_of_issues],
            ]
        );

        $this->newLine();
        $this->info('📋 Next steps:');
        $this->line('  1. View in admin: /admin/subscriptions');
        $this->line("  2. Edit subscription: /admin/subscriptions/edit/{$subscription->id}");
        $this->line("  3. View as member: Login as member and visit /member/orders/subscriptions");
        $this->line("  4. Generate order: php artisan subscriptions:generate_orders --force --subscription-id={$subscription->id}");
        $this->newLine();
        $this->comment('💡 Tip: This subscription has no initial order. The first generated order will use default delivery settings.');
        $this->comment('   For subscriptions with existing orders, delivery details are copied from the first order.');

        return 0;
    }

    private function getMember()
    {
        $memberId = $this->option('member-id');

        if ($memberId) {
            $member = Member::find($memberId);
            if (!$member) {
                $this->warn("Member ID {$memberId} not found. Searching for other members...");
            } else {
                return $member;
            }
        }

        // Get first active member
        $member = Member::query()->first();

        if (!$member) {
            return null;
        }

        return $member;
    }
}
