import { NextResponse } from "next/server";
import { createAdminClient } from "@/lib/supabase-server";
import { Buffer } from "node:buffer";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export const revalidate = 0;

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const email = searchParams.get("email");
  const normalizedEmail = (email ?? "").trim().toLowerCase();

  if (!normalizedEmail || !normalizedEmail.includes("@")) {
    return NextResponse.json({ avatarUrl: null, name: null });
  }

  try {
    const supabase = createAdminClient();
    const debugCandidates: string[] = [];
    const debugNotes: string[] = [];

    const resolveAvatarUrl = async (rawUrl: string | null | undefined) => {
      const value = (rawUrl ?? "").trim();
      if (!value) return null;
      if (value.startsWith("data:")) return value;

      const parseStorageTarget = (input: string): { bucket: string; path: string } | null => {
        const normalizePath = (pathname: string) => decodeURIComponent(pathname).replace(/^\/+/, "");
        const parseFromPath = (pathname: string) => {
          const publicMarker = "storage/v1/object/public/";
          const signMarker = "storage/v1/object/sign/";
          const signedMarker = "storage/v1/object/sign/";
          let rest = "";

          if (pathname.includes(publicMarker)) {
            rest = pathname.slice(pathname.indexOf(publicMarker) + publicMarker.length);
          } else if (pathname.includes(signMarker)) {
            rest = pathname.slice(pathname.indexOf(signMarker) + signMarker.length);
          } else if (pathname.includes(signedMarker)) {
            rest = pathname.slice(pathname.indexOf(signedMarker) + signedMarker.length);
          } else {
            rest = normalizePath(pathname);
          }

          const [bucket, ...parts] = rest.split("/");
          const path = parts.join("/");
          if (!bucket || !path) return null;
          return { bucket, path };
        };

        if (/^https?:\/\//i.test(input)) {
          try {
            const parsed = new URL(input);
            return parseFromPath(parsed.pathname);
          } catch {
            return null;
          }
        }

        return parseFromPath(input.replace(/^\/+/, ""));
      };

      const createBestUrl = async (bucket: string, path: string) => {
        const cleanPath = path.replace(/^\/+/, "");
        if (!cleanPath) return null;

        const { data: signedData, error: signedError } = await supabase.storage
          .from(bucket)
          .createSignedUrl(cleanPath, 60 * 60);
        if (!signedError && signedData?.signedUrl) return signedData.signedUrl;

        const { data: publicData } = supabase.storage.from(bucket).getPublicUrl(cleanPath);
        return publicData?.publicUrl || null;
      };

      const toDataUri = async (bucket: string, path: string) => {
        const cleanPath = path.replace(/^\/+/, "");
        if (!cleanPath) return null;
        const { data: fileData, error } = await supabase.storage.from(bucket).download(cleanPath);
        if (error || !fileData) return null;
        const arrayBuffer = await fileData.arrayBuffer();
        const base64 = Buffer.from(arrayBuffer).toString("base64");
        const mimeType = fileData.type || "image/png";
        return `data:${mimeType};base64,${base64}`;
      };

      const parsedTarget = parseStorageTarget(value);
      if (parsedTarget) {
        const bestUrl = await createBestUrl(parsedTarget.bucket, parsedTarget.path);
        if (bestUrl) return bestUrl;

        // Fallback for private buckets that still refuse direct rendering.
        const inlineDataUri = await toDataUri(parsedTarget.bucket, parsedTarget.path);
        if (inlineDataUri) return inlineDataUri;
      }

      try {
        if (/^https?:\/\//i.test(value)) {
          const url = new URL(value);
          const marker = "/storage/v1/object/public/";
          const markerIndex = url.pathname.indexOf(marker);
          if (markerIndex >= 0) {
            const rest = url.pathname.slice(markerIndex + marker.length);
            const [bucket, ...parts] = rest.split("/");
            const path = parts.join("/");
            if (bucket && path) {
              return (await createBestUrl(bucket, path)) || value;
            }
          }
          return value;
        }
      } catch {
        return value;
      }

      const cleanRaw = value
        .replace(/^storage\/v1\/object\/public\//, "")
        .replace(/^\/+/, "");
      const [bucket, ...parts] = cleanRaw.split("/");
      const path = parts.join("/");

      if (bucket && path) {
        return (await createBestUrl(bucket, path)) || value;
      }

      return (await createBestUrl("products", cleanRaw)) || value;
    };
    
    // First, try to get the user ID from users_app table (which stores all users including owners)
    let userId: string | null = null;
    let appUserId: string | null = null;
    let authUserId: string | null = null;
    let companyMembership: { user_id: string; company_id: string } | null = null;
    
    try {
      const { data: appUser } = await supabase
        .from("users_app")
        .select("id")
        .ilike("email", normalizedEmail)
        .maybeSingle();
        
      if (appUser?.id) {
        appUserId = appUser.id;
      }
    } catch (err) {
      // Ignore
    }

    // Resolve auth user id by email (used by companies.owner_id linkage)
    try {
      const adminAuth = supabase.auth.admin as any;
      if (typeof adminAuth.getUserByEmail === "function") {
        const { data: userData, error: userError } = await adminAuth.getUserByEmail(normalizedEmail);
        if (!userError && userData?.user?.id) {
          authUserId = userData.user.id;
          userId = userData.user.id;
        }
      } else if (typeof adminAuth.listUsers === "function") {
        for (let page = 1; page <= 10; page++) {
          const { data: listData, error: listError } = await adminAuth.listUsers({ page, perPage: 1000 });
          if (listError) break;
          const users = listData?.users || [];
          if (!users.length) break;
          const found = users.find((u: any) => (u.email || "").trim().toLowerCase() === normalizedEmail);
          if (found?.id) {
            authUserId = found.id;
            userId = found.id;
            break;
          }
          if (users.length < 1000) break;
        }
      }
    } catch {
      // Ignore auth admin errors
    }

    // Priority path: same logo source from Configuracoes/PDF (company owner profile)
    if (authUserId) {
      // Absolute priority: same profile updated in Configuracoes (profiles.id = auth user id)
      const { data: directAuthProfile } = await supabase
        .from("profiles")
        .select("logo_url, catalog_logo_url, store_name, catalog_name")
        .eq("id", authUserId)
        .maybeSingle();

      const directAuthLogo = directAuthProfile?.logo_url || directAuthProfile?.catalog_logo_url || null;
      if (directAuthProfile?.logo_url) debugCandidates.push("profiles.logo_url(auth)");
      if (directAuthProfile?.catalog_logo_url) debugCandidates.push("profiles.catalog_logo_url(auth)");
      if (directAuthLogo) {
        const avatarUrl = await resolveAvatarUrl(directAuthLogo);
        return NextResponse.json({
          avatarUrl,
          name:
            directAuthProfile?.store_name ||
            directAuthProfile?.catalog_name ||
            normalizedEmail.split("@")[0],
        });
      }

      const { data: companyByOwnerRows } = await supabase
        .from("companies")
        .select("id, owner_id, name")
        .eq("owner_id", authUserId)
        .limit(1);
      const companyByOwner = companyByOwnerRows?.[0] ?? null;

      if (companyByOwner?.owner_id) {
        const { data: ownerProfileByOwnerId } = await supabase
          .from("profiles")
          .select("logo_url, catalog_logo_url, store_name, catalog_name")
          .eq("id", companyByOwner.owner_id)
          .maybeSingle();

        const settingsLogo =
          ownerProfileByOwnerId?.logo_url || ownerProfileByOwnerId?.catalog_logo_url || null;
        if (ownerProfileByOwnerId?.logo_url) debugCandidates.push("profiles.logo_url(company_owner)");
        if (ownerProfileByOwnerId?.catalog_logo_url) debugCandidates.push("profiles.catalog_logo_url(company_owner)");

        if (settingsLogo) {
          const avatarUrl = await resolveAvatarUrl(settingsLogo);
          return NextResponse.json({
            avatarUrl,
            name:
              ownerProfileByOwnerId?.store_name ||
              ownerProfileByOwnerId?.catalog_name ||
              companyByOwner.name ||
              normalizedEmail.split("@")[0],
          });
        }
      }
    }

    // Fallback to auth admin if users_app fails
    if (!userId) {
      try {
        const adminAuth = supabase.auth.admin as any;
        if (typeof adminAuth.getUserByEmail === "function") {
          const { data: userData, error: userError } = await adminAuth.getUserByEmail(normalizedEmail);
          if (!userError && userData?.user?.id) {
            userId = userData.user.id;
          }
        } else if (typeof adminAuth.listUsers === "function") {
          // Use listUsers as fallback
          for (let page = 1; page <= 10; page++) {
            const { data: listData, error: listError } = await adminAuth.listUsers({ page, perPage: 1000 });
            if (listError) break;
            const users = listData?.users || [];
            if (!users.length) break;
            
            const found = users.find((u: any) => (u.email || "").trim().toLowerCase() === normalizedEmail);
            if (found?.id) {
              userId = found.id;
              break;
            }
            if (users.length < 1000) break;
          }
        }
      } catch (err) {
        // Ignore auth admin errors
      }
    }

    // Always try company_users mapping by email (canonical mapping for user_id in tenant context)
    const { data: companyUserRows } = await supabase
      .from("company_users")
      .select("user_id, company_id")
      .ilike("email", normalizedEmail)
      .eq("active", true)
      .limit(1);
    const companyUser = companyUserRows?.[0] ?? null;
    
    if (companyUser?.user_id) {
      userId = companyUser.user_id;
    }
    if (companyUser?.user_id && companyUser?.company_id) {
      companyMembership = companyUser;
    }

    if (!userId) {
      return NextResponse.json({ avatarUrl: null, name: normalizedEmail.split("@")[0] });
    }

    // Try employee_profiles first
    const { data: empProfile } = await supabase
      .from("employee_profiles")
      .select("avatar_url, full_name")
      .eq("user_id", userId)
      .maybeSingle();

    if (empProfile?.avatar_url) {
      debugCandidates.push("employee_profiles.avatar_url");
      const avatarUrl = await resolveAvatarUrl(empProfile.avatar_url);
      return NextResponse.json({ 
        avatarUrl,
        name: empProfile.full_name || normalizedEmail.split("@")[0]
      });
    }

    // Try profiles (owner)
    const { data: ownerProfile } = await supabase
      .from("profiles")
      .select("logo_url, catalog_logo_url, store_name, catalog_name")
      .eq("id", userId)
      .maybeSingle();

    const ownerDirectLogo = ownerProfile?.logo_url || ownerProfile?.catalog_logo_url || null;
    if (ownerProfile?.logo_url) debugCandidates.push("profiles.logo_url(user_id)");
    if (ownerProfile?.catalog_logo_url) debugCandidates.push("profiles.catalog_logo_url(user_id)");

    if (ownerDirectLogo) {
      const avatarUrl = await resolveAvatarUrl(ownerDirectLogo);
      return NextResponse.json({ 
        avatarUrl,
        name: ownerProfile?.store_name || ownerProfile?.catalog_name || empProfile?.full_name || normalizedEmail.split("@")[0]
      });
    }

    // If the login is from an employee, fallback to company owner's uploaded logo.
    if (!companyMembership) {
      const { data: membershipByUserRows } = await supabase
        .from("company_users")
        .select("user_id, company_id")
        .eq("user_id", userId)
        .eq("active", true)
        .limit(1);
      const membershipByUser = membershipByUserRows?.[0] ?? null;
      if (membershipByUser?.user_id && membershipByUser?.company_id) {
        companyMembership = membershipByUser;
      }
    }

    if (companyMembership?.company_id) {
      const { data: companyRow } = await supabase
        .from("companies")
        .select("owner_id, name")
        .eq("id", companyMembership.company_id)
        .maybeSingle();

      if (companyRow?.owner_id) {
        const { data: ownerByCompanyProfile } = await supabase
          .from("profiles")
          .select("logo_url, catalog_logo_url, store_name, catalog_name")
          .eq("id", companyRow.owner_id)
          .maybeSingle();

        const ownerByCompanyLogo = ownerByCompanyProfile?.logo_url || ownerByCompanyProfile?.catalog_logo_url || null;
        if (ownerByCompanyProfile?.logo_url) debugCandidates.push("profiles.logo_url(membership_owner)");
        if (ownerByCompanyProfile?.catalog_logo_url) debugCandidates.push("profiles.catalog_logo_url(membership_owner)");

        if (ownerByCompanyLogo) {
          const avatarUrl = await resolveAvatarUrl(ownerByCompanyLogo);
          return NextResponse.json({
            avatarUrl,
            name:
              ownerByCompanyProfile?.store_name ||
              ownerByCompanyProfile?.catalog_name ||
              companyRow.name ||
              empProfile?.full_name ||
              normalizedEmail.split("@")[0],
          });
        }
      }
    }

    // Final fallback for owner accounts: resolve by company billing_email and use owner profile logo
    const { data: companyByBillingRows } = await supabase
      .from("companies")
      .select("owner_id, name")
      .ilike("billing_email", normalizedEmail)
      .limit(1);
    const companyByBilling = companyByBillingRows?.[0] ?? null;

    if (companyByBilling?.owner_id) {
      const { data: ownerFromBillingProfile } = await supabase
        .from("profiles")
        .select("logo_url, catalog_logo_url, store_name, catalog_name")
        .eq("id", companyByBilling.owner_id)
        .maybeSingle();

      const ownerFromBillingLogo =
        ownerFromBillingProfile?.logo_url || ownerFromBillingProfile?.catalog_logo_url || null;
      if (ownerFromBillingProfile?.logo_url) debugCandidates.push("profiles.logo_url(billing_email)");
      if (ownerFromBillingProfile?.catalog_logo_url) debugCandidates.push("profiles.catalog_logo_url(billing_email)");

      if (ownerFromBillingLogo) {
        const avatarUrl = await resolveAvatarUrl(ownerFromBillingLogo);
        return NextResponse.json({
          avatarUrl,
          name:
            ownerFromBillingProfile?.store_name ||
            ownerFromBillingProfile?.catalog_name ||
            companyByBilling.name ||
            empProfile?.full_name ||
            normalizedEmail.split("@")[0],
        });
      }
    }

    // Extra fallback: when users_app.id is actually the company id, resolve owner profile by company id.
    if (appUserId) {
      const { data: companyByAppUserId } = await supabase
        .from("companies")
        .select("owner_id, name")
        .eq("id", appUserId)
        .maybeSingle();

      if (companyByAppUserId?.owner_id) {
        const { data: ownerFromAppUserCompany } = await supabase
          .from("profiles")
          .select("logo_url, catalog_logo_url, store_name, catalog_name")
          .eq("id", companyByAppUserId.owner_id)
          .maybeSingle();

        const ownerFromAppUserCompanyLogo =
          ownerFromAppUserCompany?.logo_url || ownerFromAppUserCompany?.catalog_logo_url || null;
        if (ownerFromAppUserCompany?.logo_url) debugCandidates.push("profiles.logo_url(users_app_company)");
        if (ownerFromAppUserCompany?.catalog_logo_url) debugCandidates.push("profiles.catalog_logo_url(users_app_company)");

        if (ownerFromAppUserCompanyLogo) {
          const avatarUrl = await resolveAvatarUrl(ownerFromAppUserCompanyLogo);
          return NextResponse.json({
            avatarUrl,
            name:
              ownerFromAppUserCompany?.store_name ||
              ownerFromAppUserCompany?.catalog_name ||
              companyByAppUserId.name ||
              empProfile?.full_name ||
              normalizedEmail.split("@")[0],
          });
        }
      }
    }

    if (!authUserId) debugNotes.push("auth_user_not_found");
    if (!companyMembership) debugNotes.push("company_membership_not_found");
    if (debugCandidates.length === 0) debugNotes.push("no_logo_field_found");

    return NextResponse.json({ 
      avatarUrl: null,
      name:
        empProfile?.full_name ||
        ownerProfile?.store_name ||
        ownerProfile?.catalog_name ||
        normalizedEmail.split("@")[0],
      debug: {
        candidates: debugCandidates,
        notes: debugNotes,
      },
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : "unknown_error";
    return NextResponse.json({
      avatarUrl: null,
      name: normalizedEmail.split("@")[0],
      debug: {
        candidates: [],
        notes: [`route_exception:${message}`],
      },
    });
  }
}
