import { createClient } from "@/lib/supabase/server";
import { NextResponse } from "next/server";

export async function POST() {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const userId = user.id;

  // Check if plan already exists
  const { data: existing } = await supabase
    .from("projects")
    .select("id")
    .eq("user_id", userId)
    .eq("name", "MaroBuilds")
    .maybeSingle();

  if (existing) {
    return NextResponse.json({ message: "Plan already exists" });
  }

  // ─── Create Projects ─────────────────────────────────────────

  const projectsToCreate = [
    { name: "MaroBuilds", icon: "🎬", color: "#ef4444", sort_order: 0 },
    { name: "Aftermoon", icon: "👕", color: "#8b5cf6", sort_order: 1 },
    { name: "Memecoins Trading", icon: "📈", color: "#f59e0b", sort_order: 2 },
    { name: "Schmidt Vermietung", icon: "🏠", color: "#10b981", sort_order: 3 },
  ];

  const { data: projects, error: pErr } = await supabase
    .from("projects")
    .insert(projectsToCreate.map((p) => ({ ...p, user_id: userId })))
    .select();

  if (pErr || !projects) {
    return NextResponse.json({ error: pErr?.message }, { status: 500 });
  }

  const projectMap: Record<string, string> = {};
  for (const p of projects) {
    projectMap[p.name] = p.id;
  }

  // ─── Create Tasks ─────────────────────────────────────────────

  const allTasks = [
    // ═══ MaroBuilds ═══
    {
      project: "MaroBuilds",
      title: "Content-Strategie erstellen",
      description:
        "Plattformen definieren (YouTube, TikTok, Instagram). Content-Pillars festlegen: Business Updates, Mindset, Behind the Scenes, Learnings. Posting-Frequenz planen.",
      priority: "urgent",
      status: "todo",
    },
    {
      project: "MaroBuilds",
      title: "Tag 1 Content aufnehmen & posten",
      description:
        "Erstes Video: Wer bin ich, was ist der Plan, warum 365 Tage. Authentic, kein Overproduction.",
      priority: "urgent",
      status: "todo",
    },
    {
      project: "MaroBuilds",
      title: "Equipment & Setup optimieren",
      description:
        "Ring Light, Mikro, Handy-Halterung, CapCut/DaVinci Resolve lernen. Content-Workflow standardisieren.",
      priority: "high",
      status: "todo",
    },
    {
      project: "MaroBuilds",
      title: "Branding Kit erstellen",
      description:
        "Logo, Farben, Thumbnail-Style, Intro/Outro für Videos. Wiedererkennungswert aufbauen.",
      priority: "high",
      status: "todo",
    },
    {
      project: "MaroBuilds",
      title: "Wochen-Review Format etablieren",
      description:
        "Jeden Sonntag ein Wochen-Review posten: Was lief, Zahlen, Learnings, Plan nächste Woche.",
      priority: "medium",
      status: "todo",
    },
    {
      project: "MaroBuilds",
      title: "Meilensteine definieren (Tag 30/90/180/365)",
      description:
        "Klare Ziele für jeden Meilenstein setzen: Follower, Umsatz, Skills, Habits. Accountability.",
      priority: "high",
      status: "todo",
    },

    // ═══ Aftermoon ═══
    {
      project: "Aftermoon",
      title: "Bestandsaufnahme — alle Produkte & Größen erfassen",
      description:
        "Komplettes Lager durchgehen, jedes Stück fotografieren und in Excel/Notion erfassen mit Größe, Farbe, EK-Preis.",
      priority: "urgent",
      status: "todo",
    },
    {
      project: "Aftermoon",
      title: "Online-Shop aktualisieren",
      description:
        "Nur noch verfügbare Produkte listen. Ausverkaufte Größen deaktivieren. Produktfotos updaten.",
      priority: "high",
      status: "todo",
    },
    {
      project: "Aftermoon",
      title: "Abverkauf-Kampagne starten",
      description:
        "Sale-Aktion auf Instagram/TikTok. Rabattcodes erstellen. Ziel: Gesamten Bestand abverkaufen ohne Neubestellung.",
      priority: "high",
      status: "todo",
    },
    {
      project: "Aftermoon",
      title: "Bundle-Deals erstellen",
      description:
        "2-for-1 oder Bundle-Angebote für langsam drehende Produkte. Mehr Wert pro Bestellung.",
      priority: "medium",
      status: "todo",
    },
    {
      project: "Aftermoon",
      title: "Content für MaroBuilds verknüpfen",
      description:
        "Aftermoon-Updates als Content für MaroBuilds nutzen. Behind the Scenes vom Abverkauf.",
      priority: "medium",
      status: "todo",
    },

    // ═══ Memecoins Trading ═══
    {
      project: "Memecoins Trading",
      title: "Trading-Grundlagen lernen",
      description:
        "Candlesticks, Support/Resistance, Volume, Market Cap verstehen. YouTube-Kurse: mindestens 10h investieren.",
      priority: "urgent",
      status: "todo",
    },
    {
      project: "Memecoins Trading",
      title: "Wallet & Tools einrichten",
      description:
        "Phantom/MetaMask Wallet, DEX-Screener, Birdeye, DexTools einrichten. Sicherheit: Hardware-Wallet für Holdings.",
      priority: "urgent",
      status: "todo",
    },
    {
      project: "Memecoins Trading",
      title: "Paper Trading — 2 Wochen ohne echtes Geld",
      description:
        "Trades aufschreiben ohne echtes Geld einzusetzen. Strategie testen, Emotionen beobachten.",
      priority: "high",
      status: "todo",
    },
    {
      project: "Memecoins Trading",
      title: "Risikomanagement-Regeln festlegen",
      description:
        "Max. Einsatz pro Trade, Stop-Loss-Strategie, Take-Profit-Levels. Niemals mehr als X% vom Portfolio pro Trade.",
      priority: "urgent",
      status: "todo",
    },
    {
      project: "Memecoins Trading",
      title: "Trading-Journal führen",
      description:
        "Jeden Trade dokumentieren: Entry, Exit, Grund, Ergebnis, Lesson. Wöchentlich auswerten.",
      priority: "high",
      status: "todo",
    },
    {
      project: "Memecoins Trading",
      title: "Community & Alpha-Gruppen finden",
      description:
        "Twitter/X Accounts folgen, Discord-Gruppen beitreten. Netzwerk aufbauen für Early Calls.",
      priority: "medium",
      status: "todo",
    },

    // ═══ Schmidt Vermietung — Phase 1: Eigenbestand ═══
    {
      project: "Schmidt Vermietung",
      title: "Firma gründen (GmbH / UG)",
      description:
        "Rechtsform klären, Notar, Handelsregister, Geschäftskonto. Steuerberater für Immobilien-GmbH finden.",
      priority: "urgent",
      status: "todo",
    },
    {
      project: "Schmidt Vermietung",
      title: "Eigenbestand erfassen & bewerten",
      description:
        "Alle eigenen Immobilien erfassen: Lage, Zustand, aktuelle Miete, Marktwert, Optimierungspotenzial.",
      priority: "urgent",
      status: "todo",
    },
    {
      project: "Schmidt Vermietung",
      title: "Vermietungsprozess standardisieren",
      description:
        "Mietverträge, Übergabeprotokolle, Mieter-Screening. Checkliste für jeden Vermietungsprozess.",
      priority: "high",
      status: "todo",
    },
    {
      project: "Schmidt Vermietung",
      title: "Verkaufsstrategie für ausgewählte Objekte",
      description:
        "Welche Objekte verkaufen? Makler beauftragen oder selbst vermarkten? Preisstrategie festlegen.",
      priority: "high",
      status: "todo",
    },
    {
      project: "Schmidt Vermietung",
      title: "Website & Branding aufbauen",
      description:
        "Professionelle Website für Schmidt Vermietung. Exposés, Kontaktformular, Referenzen.",
      priority: "medium",
      status: "todo",
    },

    // ═══ Schmidt Vermietung — Phase 2: Expansion ═══
    {
      project: "Schmidt Vermietung",
      title: "Phase 2 planen: Makler & Verwaltung",
      description:
        "Businessplan für Expansion: Verwaltung für andere, Vermietung auf Provision, Vermarktung auf Provision. Lizenzanforderungen prüfen.",
      priority: "medium",
      status: "todo",
    },
    {
      project: "Schmidt Vermietung",
      title: "Verwaltungssoftware evaluieren",
      description:
        "Tools vergleichen: Immoware, Haufe, EverReal. Mietverwaltung, Nebenkostenabrechnung, Eigentümer-Portal.",
      priority: "medium",
      status: "todo",
    },
    {
      project: "Schmidt Vermietung",
      title: "Netzwerk: Eigentümer & Investoren",
      description:
        "Kontakte zu Immobilienbesitzern aufbauen die Verwaltung/Vermietung abgeben wollen. Erste Akquise starten.",
      priority: "medium",
      status: "todo",
    },
    {
      project: "Schmidt Vermietung",
      title: "Provisionsmodelle definieren",
      description:
        "Gebührenstruktur für: Verwaltung (% der Kaltmiete), Vermietung (X Kaltmieten Provision), Verkauf (% Kaufpreis).",
      priority: "low",
      status: "todo",
    },
  ];

  const tasksToInsert = allTasks.map((t) => ({
    user_id: userId,
    project_id: projectMap[t.project],
    title: t.title,
    description: t.description,
    priority: t.priority,
    status: t.status,
  }));

  const { error: tErr } = await supabase.from("tasks").insert(tasksToInsert);

  if (tErr) {
    return NextResponse.json({ error: tErr.message }, { status: 500 });
  }

  // ─── Create Habits ────────────────────────────────────────────

  const habitsToCreate = [
    { name: "Content erstellen & posten", icon: "🎬", color: "#ef4444" },
    { name: "Trading-Journal schreiben", icon: "📈", color: "#f59e0b" },
    { name: "Immobilien-Recherche 30min", icon: "🏠", color: "#10b981" },
    { name: "Sport / Gym", icon: "💪", color: "#3b82f6" },
    { name: "Lesen 20min", icon: "📖", color: "#8b5cf6" },
    { name: "Kein Social Media Doom-Scrolling", icon: "🚫", color: "#ec4899" },
    { name: "Journaling", icon: "📝", color: "#06b6d4" },
    { name: "Wasser 3L trinken", icon: "💧", color: "#0ea5e9" },
  ];

  await supabase.from("habits").insert(
    habitsToCreate.map((h, i) => ({
      ...h,
      user_id: userId,
      sort_order: i,
    }))
  );

  // ─── Create Journal Template ──────────────────────────────────

  const journalTemplate = {
    type: "doc",
    content: [
      {
        type: "heading",
        attrs: { level: 2 },
        content: [{ type: "text", text: "Tagesreflexion" }],
      },
      {
        type: "heading",
        attrs: { level: 3 },
        content: [{ type: "text", text: "Top 3 Prioritäten heute" }],
      },
      {
        type: "orderedList",
        content: [
          { type: "listItem", content: [{ type: "paragraph", content: [{ type: "text", text: " " }] }] },
          { type: "listItem", content: [{ type: "paragraph", content: [{ type: "text", text: " " }] }] },
          { type: "listItem", content: [{ type: "paragraph", content: [{ type: "text", text: " " }] }] },
        ],
      },
      {
        type: "heading",
        attrs: { level: 3 },
        content: [{ type: "text", text: "Was habe ich heute erreicht?" }],
      },
      { type: "paragraph", content: [] },
      {
        type: "heading",
        attrs: { level: 3 },
        content: [{ type: "text", text: "MaroBuilds Update" }],
      },
      {
        type: "bulletList",
        content: [
          { type: "listItem", content: [{ type: "paragraph", content: [{ type: "text", text: "Content: " }] }] },
          { type: "listItem", content: [{ type: "paragraph", content: [{ type: "text", text: "Aftermoon: " }] }] },
          { type: "listItem", content: [{ type: "paragraph", content: [{ type: "text", text: "Trading: " }] }] },
          { type: "listItem", content: [{ type: "paragraph", content: [{ type: "text", text: "Schmidt Vermietung: " }] }] },
        ],
      },
      {
        type: "heading",
        attrs: { level: 3 },
        content: [{ type: "text", text: "Learnings & Gedanken" }],
      },
      { type: "paragraph", content: [] },
      {
        type: "heading",
        attrs: { level: 3 },
        content: [{ type: "text", text: "Dankbarkeit" }],
      },
      {
        type: "bulletList",
        content: [
          { type: "listItem", content: [{ type: "paragraph", content: [{ type: "text", text: " " }] }] },
          { type: "listItem", content: [{ type: "paragraph", content: [{ type: "text", text: " " }] }] },
          { type: "listItem", content: [{ type: "paragraph", content: [{ type: "text", text: " " }] }] },
        ],
      },
      {
        type: "heading",
        attrs: { level: 3 },
        content: [{ type: "text", text: "Morgen will ich..." }],
      },
      { type: "paragraph", content: [] },
    ],
  };

  await supabase.from("journal_templates").insert({
    user_id: userId,
    content: journalTemplate,
  });

  return NextResponse.json({
    message: "MaroBuilds plan created!",
    projects: projects.length,
    tasks: allTasks.length,
    habits: habitsToCreate.length,
  });
}
