<?php

namespace App\Console\Commands;

use App\Models\NotificationLog;
use App\Models\PointsTransaction;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ExpirePoints extends Command
{
    protected $signature = 'loyalty:expire-points';
    protected $description = 'Expire points for members whose enrolment anniversary has passed. Resets balance to 0 and extends expiry date by 1 year.';

    public function handle(): int
    {
        $today = Carbon::today();

        $members = User::where('status', 'active')
            ->whereDate('points_expiry_date', '<=', $today->toDateString())
            ->where('points_balance', '>', 0)
            ->get();

        $expired = 0;
        foreach ($members as $member) {
            DB::transaction(function () use ($member, &$expired) {
                $expiredAmount = $member->points_balance;

                // Create an expiry transaction record
                PointsTransaction::create([
                    'user_id'       => $member->id,
                    'type'          => 'expiry',
                    'amount'        => $expiredAmount,
                    'balance_after' => 0,
                    'description'   => 'Annual points expiry (enrolment anniversary)',
                    'admin_note'    => 'Automatic expiry — system scheduled task',
                    'note_visible_to_member' => true,
                ]);

                // Reset balance and extend expiry by 1 year
                $member->update([
                    'points_balance'    => 0,
                    'points_expiry_date' => $member->points_expiry_date->addYear()->toDateString(),
                ]);

                NotificationLog::create([
                    'user_id' => $member->id,
                    'type'    => 'points_expired',
                    'subject' => "{$expiredAmount} points expired",
                    'status'  => 'sent',
                    'sent_at' => now(),
                ]);

                $expired++;
            });
        }

        $this->info("Expired points for {$expired} member(s).");
        return self::SUCCESS;
    }
}
