<?php
declare(strict_types=1);

namespace FreshCloud\Mail\ImapCommands;

use FreshCloud\Mail\Log\Logger;
use FreshCloud\Mail\PocketBaseAdapter\PocketBaseAdapter;

final class InMemoryImapCommands implements ImapCommandsInterface
{
    public function __construct(
        private PocketBaseAdapter $pb,
        private Logger $logger,
    ) {}

    public function listFolders(string $userId, string $accountId): array
    {
        $this->logger->log("Listing folders for $userId:$accountId", ["user_id" => $userId, "account_id" => $accountId]);
        
        $folders = [
            new FolderInfo('INBOX'),
            new FolderInfo('Drafts'),
            new FolderInfo('Sent'),
            new FolderInfo('Trash'),
            new FolderInfo('Spam'),
            new FolderInfo('Archive'),
        ];
        
        return $folders;
    }

    public function selectFolder(string $userId, string $accountId, string $folder): array
    {
        $this->logger->log("Selecting folder '$folder' for $userId:$accountId", ["user_id" => $userId, "account_id" => $accountId]);
        
        return [
            'exists' => 150,
            'recent' => 3,
            'uidvalidity' => 123456789,
            'uidnext' => 151,
            'flags' => ['\\Seen', '\\Flagged', '\\Answered'],
            'permanentflags' => ['*', '\\Seen', '\\Flagged', '\\Answered'],
        ];
    }

    public function listMessages(string $userId, string $accountId, string $folder, int $limit = 50, int $offset = 0): array
    {
        $this->logger->log("Listing messages for $userId:$accountId in $folder (limit=$limit, offset=$offset)", ["user_id" => $userId, "account_id" => $accountId]);
        
        $messages = [];
        $startUid = $offset + 1;
        $endUid = $offset + $limit;
        
        for ($uid = $startUid; $uid <= $endUid; $uid++) {
            $messages[] = new MessageInfo(
                uid: $uid,
                folder: $folder,
                subject: "Message #$uid",
                fromAddress: "user$uid@example.com",
                fromName: "User $uid",
                date: (new \DateTimeImmutable('2023-01-01 10:00:00 UTC'))->modify("+$uid days"),
                size: $uid * 1024,
                flags: $uid % 2 === 0 ? ['\\Seen'] : [],
                hasAttachments: $uid > 100,
                messageId: "<msg$uid@example.com>",
                preview: "This is a preview for message #$uid"
            );
        }
        
        return $messages;
    }

    public function getQuota(string $userId, string $accountId): QuotaInfo
    {
        $this->logger->log("Getting quota for $userId:$accountId", ["user_id" => $userId, "account_id" => $accountId]);
        
        return new QuotaInfo(
            usedBytes: 524288000, // 500MB
            totalBytes: 2147483648, // 2GB
            usagePercent: 24.41
        );
    }

    public function searchMessages(string $userId, string $accountId, string $folder, string $criteria, int $limit = 50): array
    {
        $this->logger->log("Searching messages for '$criteria' in $folder for $userId:$accountId", ["user_id" => $userId, "account_id" => $accountId]);
        
        $allMessages = $this->listMessages($userId, $accountId, $folder, 1000);
        $results = [];
        
        foreach ($allMessages as $message) {
            if (str_contains(strtolower($message->fromAddress), strtolower($criteria)) 
                || str_contains(strtolower($message->subject), strtolower($criteria))) {
                $results[] = $message;
                if (count($results) >= $limit) {
                    break;
                }
            }
        }
        
        return $results;
    }
}