import { NextResponse } from "next/server";
import { db } from "@/app/db/db";
import { propertyStatusTracker } from "@/app/db/schema/crm/property_status_tracker";
import { eq, and } from "drizzle-orm";
import { user } from "@/app/db/schema/users";

export async function POST(req: Request) {
  console.log("📩 Incoming POST /api/property-status request");

  try {
    const {
      pipelineId,
      dealStageId,
      propertyId,
      portfolioId,
      userInfo,
      propertyMeta,
    } = await req.json();

    console.log("🧠 Parsed body:", {
      pipelineId,
      dealStageId,
      propertyId,
      portfolioId,
      userInfo,
      propertyMeta,
    });

    // 1️⃣ Check if record exists first
    console.log("🔍 Checking if record already exists in DB...");
    const existing = await db
      .select()
      .from(propertyStatusTracker)
      .where(
        and(
          eq(propertyStatusTracker.propertyId, propertyId),
          eq(propertyStatusTracker.portfolioId, portfolioId)
        )
      );

    console.log("🗃️ Existing record check result:", existing);

    if (existing.length > 0) {
      console.log("⚠️ Record already exists, skipping deal creation");
      return NextResponse.json({
        message: "Record already exists, no new deal created",
        dealId: existing[0].hubspotDealId,
      });
    }

    // 2️⃣ Create HubSpot deal
    console.log("🧱 Creating HubSpot deal...");
    const dealRes = await fetch("https://api.hubapi.com/crm/v3/objects/deals", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${process.env.HUBSPOT_API_KEY}`,
      },
      body: JSON.stringify({
        properties: {
          dealname: propertyMeta?.address || "New Property Deal",
          pipeline: pipelineId,
          dealstage: dealStageId,
        },
      }),
    });

    console.log("📡 HubSpot deal response status:", dealRes.status);

    if (!dealRes.ok) {
      const err = await dealRes.text();
      console.error("❌ HubSpot Deal creation failed:", err);
      throw new Error(`HubSpot Deal Error: ${err}`);
    }

    const dealData = await dealRes.json();
    const hubspotDealId = dealData.id;
    console.log("✅ Created HubSpot deal:", hubspotDealId);

    // 3️⃣ Retrieve user info from your DB
    console.log("👤 Fetching user info from DB...");
    const userProfile = await db
      .select()
      .from(user)
      .where(eq(user.id, userInfo.dbId))
      .limit(1);

    const userInfoFromDb = userProfile[0];
    console.log("📇 User info from DB:", userInfoFromDb);

    if (!userInfoFromDb?.email) {
      console.error("❌ User email missing in DB for user:", userInfo.dbId);
      throw new Error("User email not found; cannot create HubSpot contact.");
    }

    // 4️⃣ Create or find contact in HubSpot
    console.log("📞 Creating HubSpot contact...");
    const contactRes = await fetch("https://api.hubapi.com/crm/v3/objects/contacts", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${process.env.HUBSPOT_API_KEY}`,
      },
      body: JSON.stringify({
        properties: {
          email: userInfoFromDb.email,
        },
      }),
    });

    let hubspotContactId: string | null = null;

    console.log("📡 HubSpot contact response status:", contactRes.status);

    if (contactRes.ok) {
      const contactData = await contactRes.json();
      hubspotContactId = contactData.id;
      console.log("✅ Created new HubSpot contact:", hubspotContactId);
    } else {
      console.warn("⚠️ HubSpot contact creation failed — checking if contact exists...");

      // Check if contact already exists
      const findContactRes = await fetch(
        `https://api.hubapi.com/crm/v3/objects/contacts/search`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${process.env.HUBSPOT_API_KEY}`,
          },
          body: JSON.stringify({
            filterGroups: [
              {
                filters: [
                  {
                    propertyName: "email",
                    operator: "EQ",
                    value: userInfoFromDb.email,
                  },
                ],
              },
            ],
          }),
        }
      );

      console.log("📡 HubSpot contact search response:", findContactRes.status);

      if (findContactRes.ok) {
        const found = await findContactRes.json();
        console.log("🔎 Found contact results:", found.results);
        if (found.results?.length > 0) {
          hubspotContactId = found.results[0].id;
          console.log("✅ Found existing HubSpot contact:", hubspotContactId);
        } else {
          console.error("❌ HubSpot contact creation and lookup both failed");
          throw new Error("HubSpot contact creation and lookup both failed.");
        }
      } else {
        const findErr = await findContactRes.text();
        console.error("❌ HubSpot contact search failed:", findErr);
        throw new Error("HubSpot contact lookup request failed.");
      }
    }

    // 5️⃣ Associate contact with deal
    if (hubspotContactId) {
      console.log("🔗 Associating HubSpot deal and contact...");
      const assocUrl = `https://api.hubapi.com/crm/v3/objects/deals/${hubspotDealId}/associations/contacts/${hubspotContactId}/deal_to_contact`;

      const assocRes = await fetch(assocUrl, {
        method: "PUT",
        headers: {
          Authorization: `Bearer ${process.env.HUBSPOT_API_KEY}`,
          "Content-Type": "application/json",
        },
      });

      console.log("📡 HubSpot association response:", assocRes.status);

      if (!assocRes.ok) {
        const assocErr = await assocRes.text();
        console.warn("⚠️ HubSpot association failed:", assocErr);
      } else {
        console.log("✅ Successfully associated contact with deal");
      }
    }

    // 6️⃣ Create DB record
    console.log("🗄️ Inserting new tracker record into DB...");
    await db.insert(propertyStatusTracker).values({
      hubspotDealId,
      propertyId,
      portfolioId,
      createdAt: new Date(),
      updatedAt: new Date(),
    });

    console.log("✅ All done — returning success response");

    return NextResponse.json({
      message: "Created new tracker, HubSpot deal, and linked contact",
      dealId: hubspotDealId,
      contactId: hubspotContactId,
    });
  } catch (error: any) {
    console.error("❌ Error creating or updating HubSpot deal:", error);
    return NextResponse.json(
      { error: error.message || "Internal Server Error" },
      { status: 500 }
    );
  }
}
