<?php

namespace App\Modules\Subscription\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Responses\ApiResponse;
use App\Modules\Subscription\Models\Plan;
use App\Modules\Subscription\Requests\SwitchPlanRequest;
use App\Modules\Tenant\Models\Company;
use App\Modules\Tenant\Resources\CompanyResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class SubscriptionController extends Controller
{
    public function switchPlan(SwitchPlanRequest $request): JsonResponse
    {
        $company = $request->attributes->get('currentCompany');
        $data = $request->validated();
        $plan = Plan::query()
            ->where('is_active', true)
            ->whereKey($data['plan_id'])
            ->first();

        if (! $plan) {
            return ApiResponse::error('Plan not found', 404);
        }

        DB::transaction(function () use ($company, $plan, $data): void {
            $company->subscriptions()
                ->whereIn('status', ['trialing', 'active', 'past_due'])
                ->update([
                    'status' => 'cancelled',
                    'ends_at' => now(),
                ]);

            $company->subscriptions()->create([
                'plan_id' => $plan->id,
                'billing_cycle' => $data['billing_cycle'] ?? 'monthly',
                'status' => 'active',
                'starts_at' => now(),
                'renews_at' => ($data['billing_cycle'] ?? 'monthly') === 'yearly'
                    ? now()->addYear()
                    : now()->addMonth(),
            ]);
        });

        /** @var Company $freshCompany */
        $freshCompany = $company->fresh();

        return ApiResponse::success(
            new CompanyResource($freshCompany->load(['activeSubscription.plan.features'])),
            'Subscription plan updated successfully'
        );
    }
}
