<?php

namespace App\Http\Controllers;

use App\Services\ClaudeService;
use App\Services\NotionService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;

class ReleaseEmailController extends Controller
{
    public function __construct(
        private readonly NotionService $notion,
        private readonly ClaudeService $claude,
    ) {}

    /**
     * Generate and return a sprint release email.
     *
     * 1. Queries the Notion releases database for all "Generated" notes in the sprint.
     * 2. Passes them to Claude for email composition.
     * 3. Saves the resulting HTML back to Notion.
     * 4. Returns the HTML as a browser preview.
     *
     * Route: GET /releases/{sprint}/generate-email
     */
    public function generate(Request $request, string $sprint): Response
    {
        Log::info('ReleaseEmailController: generating email', ['sprint' => $sprint]);

        // ── 1. Fetch all documented tasks for the sprint (Tasks database) ─────
        $releaseNotes = $this->notion->releaseNotesForSprint($sprint);

        if (empty($releaseNotes)) {
            return response(
                "<h2>No generated release notes found for sprint <code>{$sprint}</code>.</h2>",
                404
            );
        }

        // ── 2. Generate HTML email via Claude ─────────────────────────────────
        $emailHtml = $this->claude->generateReleaseEmail($releaseNotes, $sprint);

        // ── 3. Save to Notion as a new page ──────────────────────────────────
        $parentId = config('services.notion.releases_parent_page_id');
        $this->notion->createPage(
            parentId: $parentId,
            title:    "📧 Release Email — {$sprint}",
            content:  [
                [
                    'object' => 'block',
                    'type'   => 'code',
                    'code'   => [
                        'language'  => 'html',
                        'rich_text' => [['type' => 'text', 'text' => ['content' => $emailHtml]]],
                    ],
                ],
            ]
        );

        // ── 4. Return HTML preview in browser ────────────────────────────────
        return response($emailHtml, 200, ['Content-Type' => 'text/html']);
    }
}