const dealDB = require("../db/deal.db")

const {  findSellerFromLink,  } = require("./seller.service")
const { makeDetailWebp, makeThumbWebp } = require("../utils/processImage");
const { v4: uuidv4 } = require("uuid");
const {uploadImage}=require("./uploadImage.service")

const dealImageDB = require("../db/dealImage.db");

async function getDeals({ q = "", page = 1, limit = 10, userId = null }) {
  const skip = (page - 1) * limit

  const queryRaw = (q ?? "").toString().trim()
  const query =
    queryRaw === "undefined" || queryRaw === "null" ? "" : queryRaw

  const where =
    query.length > 0
      ? {
          OR: [
            { title: { contains: query, mode: "insensitive" } },
            { description: { contains: query, mode: "insensitive" } },
          ],
        }
      : {}

  const [deals, total] = await Promise.all([
    dealDB.findDeals(where, {
      skip,
      take: limit,
      orderBy: { createdAt: "desc" },
      include: {
        seller: { select: { name: true, url: true } },
        user: { select: { id: true, username: true, avatarUrl: true } },
        images: {
          orderBy: { order: "asc" },
          take: 1,
          select: { imageUrl: true },
        },
      },
    }),
    dealDB.countDeals(where),
  ])

  // auth yoksa myVote=0
  if (!userId) {
    return {
      page,
      total,
      totalPages: Math.ceil(total / limit),
      results: deals.map((d) => ({ ...d, myVote: 0 })),
    }
  }

  const dealIds = deals.map((d) => d.id)

  const votes = await dealDB.findVotes(
    { userId, dealId: { in: dealIds } },
    { select: { dealId: true, voteType: true } }
  )

  const voteByDealId = new Map(votes.map((v) => [v.dealId, v.voteType]))

  return {
    page,
    total,
    totalPages: Math.ceil(total / limit),
    results: deals.map((d) => ({
      ...d,
      myVote: voteByDealId.get(d.id) ?? 0,
    })),
  }
}



async function getDealById(id) {
  const deal=await dealDB.findDeal(
    { id: Number(id) },
    {
      include: {
        seller:{
          select: {
            name:true,
            url:true
          },
        },
        user: {
          select: {
            id: true,
            username: true,
            avatarUrl: true,
          },
        },
        seller: {
          select: {
            id: true,
            name: true,
          },
        },
        images: {
          orderBy: { order: "asc" },
          select: {
            id: true,
            imageUrl: true,
            order: true,
          },
        },
        comments: {
          orderBy: { createdAt: "desc" },
          select: {
            id: true,
            text: true,
            createdAt: true,
            user: {
              select: {
                id: true,
                username: true,
                avatarUrl: true,
              },
            },
          },
        },
        _count: {
          select: {
            comments: true,
          },
        },
      },
    }
  )

  return deal
}


async function createDeal(dealCreateData, files = []) {
  // seller bağlama
  if (dealCreateData.url) {
    const seller = await findSellerFromLink(dealCreateData.url);
    if (seller) {
      dealCreateData.seller = { connect: { id: seller.id } };
      dealCreateData.customSeller = null;
    }
  }

  // 1) Deal oluştur
  const deal = await dealDB.createDeal(dealCreateData);

  // 2) Önce image işle + upload
  const rows = [];

  for (let i = 0; i < files.length && i < 5; i++) {
    const file = files[i];
    const order = i;

    const key = uuidv4();
    const basePath = `deals/${deal.id}/${key}`;
    const detailPath = `${basePath}_detail.webp`;
    const thumbPath = `${basePath}_thumb.webp`;
    const BUCKET="deal";

    const detailBuffer = await makeDetailWebp(file.buffer);
    const detailUrl = await uploadImage({
      bucket: BUCKET,
      path: detailPath,
      fileBuffer: detailBuffer,
      contentType: "image/webp",
    });

    if (order === 0) {
      const thumbBuffer = await makeThumbWebp(file.buffer);
      await uploadImage({
        bucket: BUCKET,
        path: thumbPath,
        fileBuffer: thumbBuffer,
        contentType: "image/webp",
      });
    }

    rows.push({ dealId: deal.id, order, imageUrl: detailUrl });
  }

  // 3) Uploadlar bitti -> DB’de tek seferde yaz
  if (rows.length > 0) {
    await dealImageDB.createManyDealImages(rows);
  }

  // 4) Deal + images dön
  return dealDB.getDealWithImages(deal.id);
}







module.exports = {
  getDeals,
  getDealById,
  createDeal,
}
