// middleware.ts
import { NextResponse } from 'next/server';
import { NextRequest } from 'next/server';
import { jwtVerify } from 'jose';

const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET!);
const dev = process.env.NODE_ENV !== 'production'
const HOST = process.env.NEXT_PUBLIC_SOCKET_URL
if (!dev && !HOST) {
  throw new Error('Environment variable NEXT_PUBLIC_SOCKET_URL is not set.')
}

const domain = !dev ? HOST?.replace(/https?:\/\//, '') : '0.0.0.0:8080'

export async function middleware(request: NextRequest) {
  if (process.env.NODE_ENV === 'development') {
    if (request.nextUrl.host !== domain) {
      return new Response("Invalid access point", {
        status: 500,
        statusText: "Internal Server Error",
        headers: { 'Content-Type': 'text/plain' },
      });
    }
  }

  if (request.nextUrl.pathname === "/" || request.nextUrl.pathname === "/favicon.ico") {
    const resp = await fetch(`${process.env.NEXT_PUBLIC_SOCKET_URL || 'http://localhost:8080'}/api/status`)
    const t = await resp.json()
    if (t.live) {
      if (request.nextUrl.pathname === "/favicon.ico") {
        return NextResponse.next()
      }
      const cookieRef = request.cookies.get('ref')?.value;
      const urlParams = request.nextUrl.searchParams;
      const refId = urlParams.get("ref");
      //console.log(`Cookie ref: ${cookieRef} | Url params: ${urlParams} | Ref id: ${refId} | Expected: ${t.reffrom}`)
      
      if (t.ref && t.reffrom) {
        if (cookieRef === t.reffrom) {
          return NextResponse.next();
        }
        if (refId !== t.reffrom) {
          return new Response("Unauthorized", {
            status: 403,
            headers: { 'Content-Type': 'text/plain' },
          });
        }
        const response = NextResponse.redirect(process.env.NEXT_PUBLIC_SOCKET_URL || 'http://localhost:8080');
        response.headers.set(
          'Set-Cookie',
          `ref=${refId}; Path=/; HttpOnly; Secure; SameSite=Lax`
        );
        return response;
      }
      return NextResponse.next();
    } else {
      if (request.nextUrl.pathname === "/favicon.ico") {
        return new Response("Internal Server Error", {
          status: 500,
          statusText: "Internal Server Error",
          headers: { 'Content-Type': 'text/plain' },
        });
      }
      //console.log(t)
      if (t.redirect) {
        return NextResponse.redirect(t.redirectTo)
      }
      return new Response("Internal Server Error", {
        status: 500,
        statusText: "Internal Server Error",
        headers: { 'Content-Type': 'text/plain' },
      });
    }
  }

  if (request.nextUrl.pathname.startsWith('/dashboard')) {
    if (process.env.NODE_ENV === 'development') {
      console.log('Development mode: Authentication bypassed');
      return NextResponse.next();
    }

    const token = request.cookies.get('token')?.value;

    if (!token) {
      return NextResponse.redirect(new URL('/access', request.url));
    }

    try {
      await jwtVerify(token, JWT_SECRET);
      return NextResponse.next();
    } catch (error) {
      console.error('JWT verification failed:', error);
      return NextResponse.redirect(new URL('/access', request.url));
    }
  }

  return NextResponse.next();
}

export const config = {
  matcher: '/:path*',
};
