<?php

namespace App\Services;

use App\Models\Member;
use App\Models\MembershipRenewal;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;

class MembershipRenewalService
{
    public function __construct(
        protected MembershipCertificateService $certificateService
    ) {}

    /**
     * Process a renewal for a member.
     *
     * Captures the previous end date, generates a new certificate (which
     * updates membership_end_date), then creates the MembershipRenewal record.
     *
     * @param  Member       $member
     * @param  string       $type         'manual' or 'automatic'
     * @param  int|null     $processedBy  User ID of the admin/member who triggered it (null for auto)
     * @return MembershipRenewal
     */
    public function processRenewal(Member $member, string $type = 'manual', ?int $processedBy = null): MembershipRenewal
    {
        return DB::transaction(function () use ($member, $type, $processedBy) {
            // Capture previous end date before generating new certificate
            $previousEndDate = $member->membership_end_date;

            // Generate new certificate — this also updates member->membership_end_date
            $certificate = $this->certificateService->generateForMember($member);

            // Refresh member to get the updated membership_end_date
            $member->refresh();

            // Create the renewal record
            $renewal = MembershipRenewal::create([
                'member_id'        => $member->id,
                'certificate_id'   => $certificate->id,
                'renewal_type'     => $type,
                'renewed_at'       => now(),
                'previous_end_date' => $previousEndDate,
                'new_end_date'     => $member->membership_end_date,
                'processed_by'     => $processedBy,
            ]);

            return $renewal;
        });
    }

    /**
     * Get all members eligible for automatic renewal:
     * active, auto_renewal_enabled = true, membership_end_date <= today.
     */
    public function getMembersEligibleForAutoRenewal(): Collection
    {
        return Member::where('auto_renewal_enabled', true)
            ->where('status', 'active')
            ->where('membership_end_date', '<=', today())
            ->get();
    }

    /**
     * Check whether a specific member is eligible for renewal.
     * Eligible = active AND membership_end_date is today or in the past.
     */
    public function isEligibleForRenewal(Member $member): bool
    {
        return $member->isActive()
            && $member->membership_end_date !== null
            && $member->membership_end_date->lte(today());
    }
}
