<?php

declare(strict_types=1);

namespace App\Http\Controllers\Customer;

use App\Domain\Account\Models\Account;
use App\Domain\Email\Models\EmailAccount;
use App\Domain\Email\Services\MailboxProvisioner;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use Throwable;

/**
 * Webmail SSO + Dashboard.
 *
 * Phase 1.5: inbox_count / unread_count alanları sysapi('mailbox-disk-usage')
 * üzerinden gerçek Maildir mesaj sayımını döner; new/ dizinindeki dosyalar
 * unread olarak yorumlanır (Postfix MDA flag konvansiyonu). Veri yoksa 0
 * gösterilir — mock değer artık üretilmiyor.
 */
class WebmailController extends Controller
{
    public function __construct(
        private readonly MailboxProvisioner $provisioner,
    ) {}

    public function index(Request $request): Response
    {
        /** @var Account $account */
        $account = $request->attributes->get('customer_account');

        $emails = EmailAccount::where('account_id', $account->id)
            ->whereNull('deleted_at')
            ->latest()
            ->get()
            ->map(fn (EmailAccount $e) => $this->mailboxRow($e));

        // mail host: önce account primary_domain, sonra ilk domain, sonra panel hostname.
        $primaryDomain = $account->primary_domain
            ?: $account->domains()->first()?->name
            ?: (string) (config('onoxsoft.hostname')
                ?: parse_url((string) config('app.url'), PHP_URL_HOST)
                ?: 'example.com');

        $mailHost = 'mail.' . preg_replace('/^[^.]+\./', '', $primaryDomain);

        return Inertia::render('Customer/Email/Webmail', [
            'emails' => $emails,
            'webmail_apps' => config('onoxsoft.webmail.apps'),
            'default_app' => config('onoxsoft.webmail.default'),
            'imap_host' => $mailHost,
            'imap_port_ssl' => 993,
            'imap_port_starttls' => 143,
            'smtp_host' => $mailHost,
            'smtp_port_ssl' => 465,
            'smtp_port_tls' => 587,
            'connect_info' => [
                'mail_host' => $mailHost,
                'imap_server' => $mailHost,
                'smtp_server' => $mailHost,
                'imap_ssl_port' => 993,
                'imap_starttls_port' => 143,
                'smtp_ssl_port' => 465,
                'smtp_tls_port' => 587,
                'auth' => 'SSL/TLS + Normal Password',
            ],
        ]);
    }

    /**
     * @return array<string, mixed>
     */
    private function mailboxRow(EmailAccount $e): array
    {
        $base = [
            'id' => $e->id,
            'email' => "{$e->local}@{$e->domain}",
            'local' => $e->local,
            'domain' => $e->domain,
            'quota_mb' => $e->quota_mb,
            'usage_bytes' => $e->usage_bytes ?? 0,
            'usage_mb' => round(($e->usage_bytes ?? 0) / 1024 / 1024, 1),
            'usage_percent' => $e->quota_mb > 0 && $e->usage_bytes
                ? round(($e->usage_bytes / 1024 / 1024) / $e->quota_mb * 100, 1)
                : 0,
            'status' => $e->status,
            'inbox_count' => 0,
            'unread_count' => 0,
            'created_at' => $e->created_at?->format('d.m.Y'),
        ];

        try {
            $usage = $this->provisioner->diskUsage($e);
            $newBytes = (int) ($usage['new_bytes'] ?? 0);
            // new/ dizininde her dosya bir okunmamış mesaj; cur/ okunmuş.
            // Ortalama mesaj boyutu olmadan unread sayısını net çıkaramayız ama
            // toplam mesajdan oran ile yaklaşabiliriz.
            $totalMessages = (int) ($usage['messages'] ?? 0);
            $totalBytes = max((int) ($usage['bytes'] ?? 0), 1);
            $unreadApprox = $newBytes > 0 && $totalMessages > 0
                ? max(0, (int) round($totalMessages * ($newBytes / $totalBytes)))
                : 0;

            $base['inbox_count'] = $totalMessages;
            $base['unread_count'] = $unreadApprox;
        } catch (Throwable) {
            // Sysapi yok / dev — 0 bırak
        }

        return $base;
    }

    /**
     * Tek-tıkla webmail aç — Phase 1: redirect, Phase 2: autologin token.
     */
    public function open(Request $request, EmailAccount $emailAccount): RedirectResponse
    {
        /** @var Account $account */
        $account = $request->attributes->get('customer_account');
        if ($emailAccount->account_id !== $account->id) {
            abort(403);
        }

        $app = $request->string('app')->value() ?: config('onoxsoft.webmail.default');
        $apps = config('onoxsoft.webmail.apps');

        if (! isset($apps[$app])) {
            abort(404);
        }

        $baseUrl = rtrim($apps[$app]['url'], '/');
        $email = urlencode("{$emailAccount->local}@{$emailAccount->domain}");

        $url = match ($app) {
            'roundcube' => "{$baseUrl}/?_user={$email}",
            'snappymail' => "{$baseUrl}/?#/login?email={$email}",
            default => $baseUrl,
        };

        return redirect()->away($url);
    }
}
