<?php

namespace App\Services\Support;

use App\Models\SupportRequest;
use App\Services\Email\EmailDispatchService;
use App\Services\System\GlobalConfigService;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SupportRequestService
{
    public function __construct(
        private GlobalConfigService $configService,
        private EmailDispatchService $emailService
    ) {
    }

    public function list(int $userId, array $filters, int $page, int $perPage, bool $asAdmin = false): LengthAwarePaginator
    {
        $query = SupportRequest::query()->with('user');

        if (!$asAdmin) {
            $query->where('user_id', $userId);
        } elseif (!empty($filters['user_id'])) {
            $query->where('user_id', (int) $filters['user_id']);
        }

        if (!empty($filters['status'])) {
            $query->where('status', $filters['status']);
        }

        $sortBy = $filters['sort_by'] ?? 'created_at';
        $sortDir = strtolower((string) ($filters['sort_dir'] ?? 'desc')) === 'asc' ? 'asc' : 'desc';

        return $query->orderBy($sortBy, $sortDir)
            ->paginate($perPage, ['*'], 'page', $page);
    }

    public function create(int $userId, array $payload): array
    {
        $semester = $this->configService->getSemester() ?? '';
        $schoolYear = $this->configService->getSchoolYear() ?? '';

        return DB::transaction(function () use ($userId, $payload, $semester, $schoolYear) {
            $record = SupportRequest::query()->create([
                'user_id' => $userId,
                'subject' => (string) $payload['subject'],
                'message' => (string) $payload['message'],
                'status' => 'open',
                'semester' => $semester ?: 'Fall',
                'school_year' => $schoolYear ?: '2025-2026',
            ]);

            $recipient = (string) config('support.contact_email', 'support@alrahmaisgl.org');
            $emailSent = false;
            if (!app()->runningUnitTests()) {
                $emailSent = $this->emailService->send(
                    $recipient,
                    (string) $payload['subject'],
                    nl2br((string) $payload['message']),
                    null,
                    (string) ($payload['user_email'] ?? null),
                    (string) ($payload['user_name'] ?? null)
                );
            }

            if (!$emailSent) {
                Log::warning('Support email failed for user ' . $userId);
            }

            return [
                'record' => $record,
                'email_sent' => $emailSent,
                'recipient' => $recipient,
            ];
        });
    }
}
