<?php
declare(strict_types=1);

namespace FreshCloud\Mail\Identity;

final class InMemoryIdentityProvider implements IdentityProvider
{
    private array $accounts = [];
    private array $active = [];

    public function __construct()
    {
        // Initialize default user accounts
        $this->accounts['user123'] = [
            [
                'id' => 'acc1',
                'email' => 'mark@treeschedulers.uk',
                'name' => 'Mark Treescheduler',
            ],
            [
                'id' => 'acc2',
                'email' => 'personal@gmail.com',
                'name' => 'Personal Gmail',
            ],
        ];
        $this->active['user123'] = 'acc1';
    }

    public function getFromAddress(string $userId, string $accountId): string
    {
        $accounts = $this->accounts[$userId] ?? [];
        foreach ($accounts as $account) {
            if ($account['id'] === $accountId) {
                return $account['email'];
            }
        }
        throw new \RuntimeException("Account not found: $accountId");
    }

    public function getAllAccounts(string $userId): array
    {
        return $this->accounts[$userId] ?? [];
    }

    public function getActiveAccountId(string $userId): string
    {
        return $this->active[$userId] ?? throw new \RuntimeException("No active account for user");
    }

    public function setActiveAccountId(string $userId, string $accountId): bool
    {
        if (!isset($this->accounts[$userId])) {
            throw new \RuntimeException("User not found");
        }
        
        $valid = false;
        foreach ($this->accounts[$userId] as $account) {
            if ($account['id'] === $accountId) {
                $valid = true;
                break;
            }
        }
        
        if (!$valid) {
            throw new \RuntimeException("Invalid account ID");
        }
        
        $this->active[$userId] = $accountId;
        return true;
    }

    // ... other existing methods ...
}