import { prisma } from './prisma'
import type { ListingFilter } from './types'
import type { Prisma } from '@prisma/client'

function buildWhere(filter: ListingFilter): Prisma.ListingWhereInput {
  const where: Prisma.ListingWhereInput = {}
  where.status = 'PUBLISHED'
  if (filter.category) where.category = filter.category
  if (filter.country) where.country = filter.country
  if (filter.stage) where.stage = filter.stage
  if (filter.verifiedOnly) where.verified = true
  if (filter.commodity) where.commodities = { some: { commodity: filter.commodity } }
  if (filter.dealType) where.dealTypes = { some: { dealType: filter.dealType } }
  if (filter.priceMin != null || filter.priceMax != null) {
    where.priceUsd = {}
    if (filter.priceMin != null) where.priceUsd.gte = filter.priceMin
    if (filter.priceMax != null) where.priceUsd.lte = filter.priceMax
  }
  if (filter.surfaceMin != null || filter.surfaceMax != null) {
    where.surfaceHa = {}
    if (filter.surfaceMin != null) where.surfaceHa.gte = filter.surfaceMin
    if (filter.surfaceMax != null) where.surfaceHa.lte = filter.surfaceMax
  }
  return where
}

function buildOrderBy(sort: ListingFilter['sort']): Prisma.ListingOrderByWithRelationInput {
  if (sort === 'precio_asc') return { priceUsd: 'asc' }
  if (sort === 'precio_desc') return { priceUsd: 'desc' }
  return { publishedAt: 'desc' }
}

export async function getListings(filter: ListingFilter) {
  return prisma.listing.findMany({
    where: buildWhere(filter),
    orderBy: buildOrderBy(filter.sort),
    include: { commodities: true, dealTypes: true },
  })
}

export async function getListingsByOwner(ownerId: string) {
  return prisma.listing.findMany({
    where: { ownerId },
    orderBy: { publishedAt: 'desc' },
    include: { commodities: true, dealTypes: true },
  })
}

export async function getListingBySlug(slug: string) {
  return prisma.listing.findUnique({
    where: { slug },
    include: { commodities: true, dealTypes: true },
  })
}

export async function getMarketStats() {
  const [count, agg, countries] = await Promise.all([
    prisma.listing.count(),
    prisma.listing.aggregate({ _sum: { priceUsd: true } }),
    prisma.listing.findMany({ select: { country: true }, distinct: ['country'] }),
  ])
  return { count, totalUsd: agg._sum.priceUsd ?? 0, countryCount: countries.length }
}

export type ListingWithRelations = Awaited<ReturnType<typeof getListings>>[number]
