<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Helpers\Response;
use App\Services\LeadService;
use App\Services\GoogleSheetsService;

class ExportController extends BaseController
{
    private LeadService $leadService;

    public function __construct($request)
    {
        parent::__construct($request);
        $this->leadService = new LeadService();
    }

    public function exportLeads(): void
    {
        $filters = [
            'event_id' => $this->getAuthUserEventId(),
            'status' => $this->request->query('status'),
            'source' => $this->request->query('source'),
            'search' => $this->request->query('search'),
        ];

        try {
            $filePath = $this->leadService->exportLeads(
                $filters,
                $this->getAuthUserId(),
                $this->getAuthUserRole()
            );

            $fileName = basename($filePath);

            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment; filename="' . $fileName . '"');
            header('Content-Length: ' . filesize($filePath));
            readfile($filePath);
            exit;
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function exportToSheets(): void
    {
        $data = $this->request->body();
        $spreadsheetId = $data['spreadsheet_id'] ?? '';

        if (empty($spreadsheetId)) {
            Response::error('El ID de la hoja de cálculo es obligatorio', 422);
        }

        $filters = [
            'event_id' => $this->getAuthUserEventId(),
            'status' => $data['status'] ?? null,
            'source' => $data['source'] ?? null,
            'search' => $data['search'] ?? null,
        ];

        try {
            $result = $this->leadService->getLeads(
                $this->getAuthUserId(),
                $this->getAuthUserRole(),
                $filters,
                1,
                1000
            );

            $sheets = new GoogleSheetsService();
            $export = $sheets->exportLeads($result['items'], $spreadsheetId, $data['sheet_name'] ?? 'Leads');

            Response::success($export, 'Leads exportados a Google Sheets correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }
}
