<?php

declare(strict_types=1);

namespace App\Services;

class GoogleSheetsService
{
    private bool $configured;

    public function __construct()
    {
        $config = require BASE_PATH . '/config/google.php';
        $this->configured = !empty($config['sheets']['key_file']);
    }

    public function isConfigured(): bool
    {
        return $this->configured;
    }

    private function getClient(): \Google\Service\Sheets
    {
        if (!$this->configured) {
            throw new \RuntimeException('Google Sheets no está configurado', 400);
        }

        $config = require BASE_PATH . '/config/google.php';

        if (!file_exists($config['sheets']['key_file'])) {
            throw new \RuntimeException('Archivo de credenciales de Google Sheets no encontrado', 400);
        }

        $client = new \Google\Client();
        $client->setAuthConfig($config['sheets']['key_file']);
        $client->addScope(\Google\Service\Sheets::SPREADSHEETS);

        return new \Google\Service\Sheets($client);
    }

    private function leadToRow(array $lead): array
    {
        $clientType = !empty($lead['client_type']) ? (is_array($lead['client_type']) ? implode(', ', $lead['client_type']) : $lead['client_type']) : '';
        $industry = !empty($lead['industry']) ? (is_array($lead['industry']) ? implode(', ', $lead['industry']) : $lead['industry']) : '';
        return [
            $lead['first_name'] ?? '',
            $lead['last_name'] ?? '',
            $lead['email'] ?? '',
            $lead['phone'] ?? '',
            $lead['company'] ?? '',
            $lead['position'] ?? '',
            $lead['city'] ?? '',
            $lead['region'] ?? '',
            $clientType,
            $industry,
            $lead['classification'] ?? '',
            $lead['observations'] ?? '',
            $lead['status'] ?? '',
            $lead['source'] ?? '',
            $lead['created_at'] ?? '',
        ];
    }

    public function exportLeads(array $leads, string $spreadsheetId, string $sheetName = 'Leads'): array
    {
        try {
            $service = $this->getClient();

            $headers = ['Nombre', 'Apellido', 'Email', 'Teléfono', 'Empresa', 'Cargo', 'Ciudad', 'Región', 'Tipo Cliente', 'Rubro', 'Clasificación', 'Observaciones', 'Estado', 'Origen', 'Fecha'];
            $values = [$headers];

            foreach ($leads as $lead) {
                $values[] = $this->leadToRow($lead);
            }

            $body = new \Google\Service\Sheets\ValueRange(['values' => $values]);
            $service->spreadsheets_values->update(
                $spreadsheetId,
                $sheetName . '!A1',
                $body,
                ['valueInputOption' => 'RAW']
            );

            return [
                'success' => true,
                'rows' => count($leads),
                'spreadsheet_id' => $spreadsheetId,
            ];
        } catch (\Exception $e) {
            error_log('Google Sheets error: ' . $e->getMessage());
            throw new \RuntimeException('Error al exportar a Google Sheets: ' . $e->getMessage(), 500);
        }
    }

    public function appendLead(array $lead, string $spreadsheetId, string $sheetName = 'Leads'): array
    {
        try {
            $service = $this->getClient();

            $row = $this->leadToRow($lead);
            $body = new \Google\Service\Sheets\ValueRange(['values' => [$row]]);

            $service->spreadsheets_values->append(
                $spreadsheetId,
                $sheetName . '!A:O',
                $body,
                ['valueInputOption' => 'RAW', 'insertDataOption' => 'INSERT_ROWS']
            );

            return ['success' => true];
        } catch (\Exception $e) {
            error_log('Google Sheets append error: ' . $e->getMessage());
            throw new \RuntimeException('Error al agregar lead a Google Sheets: ' . $e->getMessage(), 500);
        }
    }
}
