<?php

namespace App\Services\Communication;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class CommunicationTemplateService
{
    public function listActiveTemplates(): array
    {
        [$keyColumn, $bodyColumn] = $this->resolveTemplateColumns();

        return DB::table('email_templates')
            ->where('is_active', 1)
            ->orderBy($keyColumn, 'asc')
            ->get()
            ->map(function ($row) use ($keyColumn, $bodyColumn) {
                $row = (array) $row;
                return [
                    'template_key' => (string) ($row[$keyColumn] ?? ''),
                    'subject' => (string) ($row['subject'] ?? ''),
                    'body' => (string) ($row[$bodyColumn] ?? ''),
                ];
            })
            ->all();
    }

    public function findTemplateByKey(string $key): ?array
    {
        [$keyColumn, $bodyColumn] = $this->resolveTemplateColumns();

        $row = DB::table('email_templates')
            ->where($keyColumn, $key)
            ->where('is_active', 1)
            ->first();

        if (!$row) {
            return null;
        }

        $row = (array) $row;

        return [
            'template_key' => (string) ($row[$keyColumn] ?? ''),
            'subject' => (string) ($row['subject'] ?? ''),
            'body' => (string) ($row[$bodyColumn] ?? ''),
        ];
    }

    private function resolveTemplateColumns(): array
    {
        $keyColumn = Schema::hasColumn('email_templates', 'template_key') ? 'template_key' : 'code';
        $bodyColumn = Schema::hasColumn('email_templates', 'body') ? 'body' : 'body_html';
        return [$keyColumn, $bodyColumn];
    }
}
