import { NextResponse } from "next/server";
import {
  attachSessionCookies,
  initialsFromName,
  type SessionUser,
} from "@/lib/auth/session";

const DEMO_USER: SessionUser = {
  id: "demo_user",
  name: "Sarah Mitchell",
  email: "sarah@postsync.pro",
  initials: "SM",
};

function resolveDemoUser(email: string, password: string): SessionUser | null {
  const demoEmail = process.env.AUTH_DEMO_EMAIL ?? DEMO_USER.email;
  const demoPassword = process.env.AUTH_DEMO_PASSWORD ?? "demo";

  if (email.trim().toLowerCase() !== demoEmail.toLowerCase()) return null;
  if (password !== demoPassword) return null;

  return DEMO_USER;
}

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as { email?: string; password?: string };
    const email = body.email?.trim() ?? "";
    const password = body.password ?? "";

    if (!email || !password) {
      return NextResponse.json({ error: "Email and password are required." }, { status: 400 });
    }

    const user = resolveDemoUser(email, password);
    if (!user) {
      return NextResponse.json({ error: "Invalid email or password." }, { status: 401 });
    }

    const response = NextResponse.json({ success: true, user });
    return attachSessionCookies(response, user);
  } catch {
    return NextResponse.json({ error: "Login failed." }, { status: 500 });
  }
}

export async function PUT(request: Request) {
  try {
    const body = (await request.json()) as { name?: string; email?: string; password?: string };
    const name = body.name?.trim() ?? "";
    const email = body.email?.trim() ?? "";
    const password = body.password ?? "";

    if (!name || !email || !password) {
      return NextResponse.json(
        { error: "Name, email, and password are required." },
        { status: 400 },
      );
    }

    if (password.length < 4) {
      return NextResponse.json(
        { error: "Password must be at least 4 characters." },
        { status: 400 },
      );
    }

    const user: SessionUser = {
      id: `user_${Date.now()}`,
      name,
      email,
      initials: initialsFromName(name) || "U",
    };

    const response = NextResponse.json({ success: true, user });
    return attachSessionCookies(response, user);
  } catch {
    return NextResponse.json({ error: "Sign up failed." }, { status: 500 });
  }
}
