<?php

namespace App\Services;

use App\Models\AjoGroup;
use App\Models\Payout;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class PayoutService
{
    public function save(array $data, ?Payout $payout = null): Payout
    {
        return DB::transaction(function () use ($data, $payout): Payout {
            $valid = AjoGroup::findOrFail($data['ajo_group_id'])->members()->whereKey($data['member_id'])->exists();
            throw_unless($valid, ValidationException::withMessages(['member_id' => 'This member is not enrolled in the selected group.']));
            $data['amount'] = (int) round(((float) $data['amount']) * 100);
            $data['collection_date'] = $data['status'] === 'paid' ? ($data['collection_date'] ?? now()) : $data['collection_date'];

            if ($payout) {
                $locked = Payout::lockForUpdate()->findOrFail($payout->id);
                $locked->update($data);

                return $locked->refresh();
            }

            return Payout::create($data);
        });
    }
}
