<?php

namespace App\Repos;

use App\Models\Credit;

class CreditRepo
{
    public static function create($credit)
    {
        return Credit::create($credit);
    }

    public static function findByUserId(int $userId)
    {
        return Credit::with(['user.subscription', 'user.plan'])
            ->where('user_id', $userId)
            ->first();
    }

    public static function updateById(int $id, array $data)
    {
        $credit = Credit::findOrFail($id);
        $credit->update($data);
        return $credit->fresh();
    }

    public static function decrementByUserId(int $userId, string $module)
    {
        $credit = Credit::where('user_id', $userId)->first();
        $amount = max($credit[$module] - 1, 0);
        $credit->update([$module => $amount]);
        return $credit->fresh();
    }
}
