package queries

const GetActiveMarketsForMapping = `
SELECT
  p.id,
  p.code,
  p.title
FROM mk_sales_piy p
WHERE p.is_active = true
ORDER BY p.title, p.code
`

const GetActiveMailsForMapping = `
SELECT
  m.id::text,
  m.email,
  COALESCE(NULLIF(m.display_name, ''), m.email) AS display_name
FROM mk_mail m
WHERE m.is_active = true
ORDER BY m.email
`

const GetMarketMailMappingRows = `
SELECT
  p.id,
  p.code,
  p.title,
  m.id::text,
  m.email,
  COALESCE(NULLIF(m.display_name, ''), m.email) AS display_name
FROM mk_sales_piy p
LEFT JOIN mk_market_mail mm
  ON mm.market_id = p.id
LEFT JOIN mk_mail m
  ON m.id = mm.mail_id
  AND m.is_active = true
WHERE p.is_active = true
ORDER BY p.title, p.code, m.email
`

const ExistsActiveMarketByID = `
SELECT EXISTS (
  SELECT 1
  FROM mk_sales_piy p
  WHERE p.id = $1
    AND p.is_active = true
)
`

const ExistsActiveMailByID = `
SELECT EXISTS (
  SELECT 1
  FROM mk_mail m
  WHERE m.id = $1
    AND m.is_active = true
)
`

const DeleteMarketMailsByMarketID = `
DELETE FROM mk_market_mail
WHERE market_id = $1
`

const InsertMarketMailMapping = `
INSERT INTO mk_market_mail (market_id, mail_id)
VALUES ($1, $2)
`
