/**
 * Auto-Trigger Config API
 * GET - Get auto-review-request settings for the user
 * PUT - Update auto-review-request settings (enable/disable, delay hours)
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getEffectiveOwnerId } from "@/lib/utils/organization-data";
import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";
import { z } from "zod";
import { getDataSource } from "@/lib/data-source";

const log = logger.scope("AutoTriggerConfigAPI");

const AutoTriggerConfigSchema = z.object({
  enabled: z.boolean(),
  delayHours: z.number().int().min(1).max(168).default(24),
  channels: z
    .array(z.enum(["email", "whatsapp"]))
    .min(1)
    .default(["email"]),
});

interface AutoTriggerConfig {
  enabled: boolean;
  delayHours: number;
  channels: string[];
}

const DEFAULT_CONFIG: AutoTriggerConfig = {
  enabled: false,
  delayHours: 24,
  channels: ["email"],
};

export async function GET(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const effectiveUserId = await getEffectiveOwnerId(user.userId);

    if (getDataSource("reviews") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");
        const widgetSettings = await convexQuery(
          "reviews/queries:getWidgetSettings",
          {
            userId: effectiveUserId,
          },
        );
        let config = DEFAULT_CONFIG;
        if (
          widgetSettings &&
          typeof widgetSettings === "object" &&
          "customCss" in widgetSettings
        ) {
          try {
            const parsedCss = JSON.parse(
              (widgetSettings as Record<string, string>).customCss ?? "",
            );
            if (parsedCss?.autoTrigger) {
              config = { ...DEFAULT_CONFIG, ...parsedCss.autoTrigger };
            }
          } catch {
            // Not JSON, use defaults
          }
        }
        return NextResponse.json({ success: true, config });
      } catch {
        // Fall through to Prisma
      }
    }

    const settings = await prisma.review_widget_settings.findUnique({
      where: { userId: effectiveUserId },
      select: { customCss: true },
    });

    // Store auto-trigger config in customCss field as JSON prefix (pragmatic reuse)
    // In production, this would be a dedicated column or model
    let config = DEFAULT_CONFIG;
    if (settings?.customCss) {
      try {
        const parsed = JSON.parse(settings.customCss);
        if (parsed?.autoTrigger) {
          config = { ...DEFAULT_CONFIG, ...parsed.autoTrigger };
        }
      } catch {
        // Not JSON — it's actual CSS, use defaults
      }
    }

    return NextResponse.json({ success: true, config });
  } catch (error) {
    log.error("Failed to get auto-trigger config", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

export async function PUT(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const effectiveUserId = await getEffectiveOwnerId(user.userId);
    const body = await request.json();
    const parsed = AutoTriggerConfigSchema.safeParse(body);

    if (!parsed.success) {
      return NextResponse.json(
        { success: false, error: parsed.error.flatten() },
        { status: 400 },
      );
    }

    if (getDataSource("reviews") === "convex") {
      try {
        const { convexQuery, convexMutation } =
          await import("@/lib/convex-client");

        // Read existing widget settings to preserve other data
        const existing = await convexQuery(
          "reviews/queries:getWidgetSettings",
          {
            userId: effectiveUserId,
          },
        );

        let storedData: Record<string, unknown> = {};
        if (
          existing &&
          typeof existing === "object" &&
          "customCss" in existing
        ) {
          try {
            storedData = JSON.parse(
              (existing as Record<string, string>).customCss ?? "",
            );
          } catch {
            storedData = (existing as Record<string, string>).customCss
              ? { css: (existing as Record<string, string>).customCss }
              : {};
          }
        }

        storedData.autoTrigger = parsed.data;

        await convexMutation("reviews/mutations:updateWidgetSettings", {
          userId: effectiveUserId,
          customCss: JSON.stringify(storedData),
        });

        return NextResponse.json({ success: true, config: parsed.data });
      } catch {
        // Fall through to Prisma
      }
    }

    // Read existing customCss to preserve actual CSS
    const existing = await prisma.review_widget_settings.findUnique({
      where: { userId: effectiveUserId },
      select: { customCss: true },
    });

    let storedData: Record<string, unknown> = {};
    if (existing?.customCss) {
      try {
        storedData = JSON.parse(existing.customCss);
      } catch {
        // Was actual CSS — wrap it
        storedData = { css: existing.customCss };
      }
    }

    storedData.autoTrigger = parsed.data;

    await prisma.review_widget_settings.upsert({
      where: { userId: effectiveUserId },
      update: { customCss: JSON.stringify(storedData) },
      create: {
        id: effectiveUserId,
        userId: effectiveUserId,
        customCss: JSON.stringify(storedData),
      },
    });

    return NextResponse.json({ success: true, config: parsed.data });
  } catch (error) {
    log.error("Failed to update auto-trigger config", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
