<?php

namespace App\Core\Services\Accounting;

use App\Core\Repositories\ChartOfAccountRepository;
use App\Models\ChartOfAccount;
use Exception;

/**
 * Chart of Accounts Service
 * Handles chart of accounts business logic
 */
class ChartOfAccountService
{
    public function __construct(
        private ChartOfAccountRepository $repository
    ) {}

    /**
     * Create a new account
     */
    public function create(array $data): ChartOfAccount
    {
        // Validate code uniqueness
        if ($this->repository->getByCode($data['code'])) {
            throw new Exception('Account code already exists.');
        }

        return $this->repository->create($data);
    }

    /**
     * Update an account
     */
    public function update(ChartOfAccount $account, array $data): ChartOfAccount
    {
        // Prevent updating system accounts
        if ($account->is_system && isset($data['code'])) {
            throw new Exception('System account code cannot be changed.');
        }

        // Validate code uniqueness if changed
        if (isset($data['code']) && $data['code'] !== $account->code) {
            if ($this->repository->getByCode($data['code'])) {
                throw new Exception('Account code already exists.');
            }
        }

        $this->repository->update($account, $data);

        return $account->fresh();
    }

    /**
     * Delete an account
     */
    public function delete(ChartOfAccount $account): bool
    {
        return $this->repository->delete($account);
    }

    /**
     * Get accounts grouped by type
     */
    public function getGroupedByType(): array
    {
        $accounts = $this->repository->getAll();
        $grouped = [];

        foreach ($accounts as $account) {
            if (! isset($grouped[$account->type])) {
                $grouped[$account->type] = [];
            }
            $grouped[$account->type][] = $account;
        }

        return $grouped;
    }
}
