import { NextRequest, NextResponse } from "next/server";
import { getStaffSession } from "@/lib/staff-session";
import { prisma } from "@/lib/db";
import { systemMessagesAdapter } from "@/lib/adapters/system";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";

// GET: Fetch all messages (admin only)
export async function GET(req: NextRequest) {
  try {
    void req;
    const user = await getStaffSession();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    if (user.role !== "ADMIN" && user.role !== "SUPER_ADMIN") {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    // Convex branch
    if (getDataSource("support") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");
        const messages = await convexQuery(
          "support/queries:getSystemMessages",
          {},
        );

        if (messages) {
          return NextResponse.json(messages);
        }
      } catch (convexError) {
        console.error(
          "Convex system messages fetch failed, falling back to Prisma:",
          convexError,
        );
        // Fall through to Prisma
      }
    }

    const messages = await systemMessagesAdapter.findMany({
      orderBy: { createdAt: "desc" },
      include: {
        _count: {
          select: { views: true },
        },
      },
    });

    return NextResponse.json(messages);
  } catch (error) {
    logger.error("Failed to fetch messages", error);
    return NextResponse.json(
      { error: "Failed to fetch messages" },
      { status: 500 },
    );
  }
}

// POST: Create a new message
export async function POST(req: NextRequest) {
  try {
    const user = await getStaffSession();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    if (user.role !== "ADMIN" && user.role !== "SUPER_ADMIN") {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    const body = await req.json();
    const { type, title, message, expiresInHours } = body;
    const normalizedType = ["info", "warning", "error", "maintenance"].includes(
      type,
    )
      ? type
      : "info";
    const safeMessage = typeof message === "string" ? message.trim() : "";

    if (!safeMessage) {
      return NextResponse.json(
        { error: "Message is required" },
        { status: 400 },
      );
    }

    let expiresAt: Date | null = null;
    if (expiresInHours && expiresInHours !== "0") {
      expiresAt = new Date();
      expiresAt.setHours(expiresAt.getHours() + parseInt(expiresInHours));
    }

    // Convex branch
    if (getDataSource("support") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        const convexId = await convexMutation(
          "support/mutations:createSystemMessage",
          {
            type: normalizedType,
            title,
            message: safeMessage,
            createdBy: user.id,
            expiresAt: expiresAt ? expiresAt.getTime() : undefined,
          },
        );

        return NextResponse.json({
          id: convexId,
          type: normalizedType,
          title,
          message: safeMessage,
          createdBy: user.id,
          expiresAt: expiresAt?.toISOString() || null,
          isActive: true,
          createdAt: new Date().toISOString(),
        });
      } catch (convexError) {
        console.error(
          "Convex system message create failed, falling back to Prisma:",
          convexError,
        );
        // Fall through to Prisma
      }
    }

    const newMessage = await systemMessagesAdapter.create({
      data: {
        type: normalizedType,
        title,
        message: safeMessage,
        expiresAt,
        createdBy: user.id,
      },
    });

    return NextResponse.json(newMessage);
  } catch (error) {
    logger.error("Create message error", error);
    return NextResponse.json(
      {
        error:
          error instanceof Error ? error.message : "Failed to create message",
      },
      { status: 500 },
    );
  }
}

// DELETE: Remove a message
export async function DELETE(req: NextRequest) {
  try {
    const user = await getStaffSession();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    if (user.role !== "ADMIN" && user.role !== "SUPER_ADMIN") {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    const { searchParams } = new URL(req.url);
    const id = searchParams.get("id");

    if (!id)
      return NextResponse.json({ error: "ID required" }, { status: 400 });

    // Convex branch
    if (getDataSource("support") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        await convexMutation("support/mutations:deleteSystemMessage", {
          id: id as any,
        });

        return NextResponse.json({ success: true });
      } catch (convexError) {
        console.error(
          "Convex system message delete failed, falling back to Prisma:",
          convexError,
        );
        // Fall through to Prisma
      }
    }

    await systemMessagesAdapter.delete({
      where: { id },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    logger.error("Failed to delete message", error);
    return NextResponse.json(
      { error: "Failed to delete message" },
      { status: 500 },
    );
  }
}
