-- ============================================================================
-- V47 — 데모 로그인 해소 행사(e-2026-live) 폐루프 보강 (정산·옥션·관람객/리드·마케팅)
-- ============================================================================
-- 배경(근본 원인): 데모 계정(demo-organizer/exhibitor/contractor)은
--   ① e-2026-smf (V38, 8월 개막)  ② e-2026-live (V39, 오늘 개막) 두 행사의 event_member.
--   워크스페이스 정렬 = findEventRoles ORDER BY e.start_date → 오늘 개막인 e-2026-live 가 선두.
--   프론트 useResolvedEventId = currentEventId ?? workspaces[0].eventId → 'e-2026-live'.
-- 문제: 정산(invoice/payment/tax/refund)·옥션(auction/bid/award)·관람객(visitor)·리드(lead)·
--   마케팅(edm/sponsorship) 데모 데이터는 전부 e-2026-smf 또는 V42 bulk(bd-e-*)에만 존재 →
--   로그인 후 해소되는 e-2026-live 스코프에서 정산·옥션·관람객 화면이 "빈 상태"로 보였다.
-- 조치: e-2026-live 를 축으로 각 도메인 폐루프를 멱등 보강(기존 시드 불변, ON CONFLICT DO NOTHING).
--   e-2026-live 참가업체(부스 assigned_company_name/booth_sale.sold_to_company):
--     (주)스마트오토메이션·델타로보틱스·글로벌테크·미래제조연구소·한국센서테크·바이오헬스랩
--   PII 는 전부 더미(홍길동·010-0000-*·*@kintex.test). tenant_id='KINTEX'.
-- ============================================================================


-- ============================================================================
-- 1) 정산 폐루프 — 청구서(상태 분포) + 수납 + 세금계산서 + 환불
-- ============================================================================
-- invoice UNIQUE(event_id, exhibitor_name) → 행사당 참가업체명 1건(멱등). 상태 분포:
--   paid×2 · invoiced(부분수납)×2 · overdue×1 · pending×2 · cancelled(환불대상)×1
INSERT INTO invoice (id, event_id, exhibitor_id, exhibitor_name, invoice_no, category, source_ref,
                     subtotal, vat, total, paid_amount, status, due_date, issued_at, paid_at,
                     cancelled_at, cancel_reason, line_items, note, created_by) VALUES
  -- 완납
  ('inv-live-01','e-2026-live',NULL,'(주)스마트오토메이션','LIVE-2026-0001','rental',NULL,
     6534000, 653400, 7187400, 7187400, 'paid', CURRENT_DATE - 2, now()-interval '18 day', now()-interval '5 day',
     NULL, NULL,
     '[{"category":"RENTAL","description":"부스 임대료 (18㎡ 아일랜드 · L-101)","quantity":18,"unitPrice":363000,"amount":6534000}]'::jsonb,
     '완납 처리.', 'system-seed'),
  ('inv-live-03','e-2026-live',NULL,'글로벌테크','LIVE-2026-0003','rental',NULL,
     4356000, 435600, 4791600, 4791600, 'paid', CURRENT_DATE - 1, now()-interval '10 day', now()-interval '3 day',
     NULL, NULL,
     '[{"category":"RENTAL","description":"부스 임대료 (18㎡ 조립부스 · L-103)","quantity":18,"unitPrice":242000,"amount":4356000}]'::jsonb,
     '완납 처리.', 'system-seed'),
  -- 부분수납(발행)
  ('inv-live-02','e-2026-live',NULL,'델타로보틱스','LIVE-2026-0002','rental',NULL,
     5445000, 544500, 5989500, 2395800, 'invoiced', CURRENT_DATE + 7, now()-interval '14 day', NULL,
     NULL, NULL,
     '[{"category":"RENTAL","description":"부스 임대료 (18㎡ 독립부스 · L-102)","quantity":18,"unitPrice":302500,"amount":5445000}]'::jsonb,
     '계약금 40% 수납.', 'system-seed'),
  ('inv-live-06','e-2026-live',NULL,'바이오헬스랩','LIVE-2026-0006','rental',NULL,
     4356000, 435600, 4791600, 1916640, 'invoiced', CURRENT_DATE + 10, now()-interval '6 day', NULL,
     NULL, NULL,
     '[{"category":"RENTAL","description":"부스 임대료 (18㎡ 조립부스 · L-108)","quantity":18,"unitPrice":242000,"amount":4356000}]'::jsonb,
     '계약금 40% 수납.', 'system-seed'),
  -- 연체(overdue) — 대시보드 overdueCount 활성화
  ('inv-live-04','e-2026-live',NULL,'미래제조연구소','LIVE-2026-0004','rental',NULL,
     4791600, 479160, 5270760, 0, 'overdue', CURRENT_DATE - 5, now()-interval '20 day', NULL,
     NULL, NULL,
     '[{"category":"RENTAL","description":"부스 임대료 (18㎡ 코너부스 · L-104)","quantity":18,"unitPrice":266200,"amount":4791600}]'::jsonb,
     '납부 기한 경과 — 독촉 대상.', 'system-seed'),
  -- 발행 대기(pending)
  ('inv-live-05','e-2026-live',NULL,'한국센서테크','LIVE-2026-0005','rental',NULL,
     4356000, 435600, 4791600, 0, 'pending', CURRENT_DATE + 14, NULL, NULL,
     NULL, NULL,
     '[{"category":"RENTAL","description":"부스 임대료 (18㎡ 조립부스 · L-106)","quantity":18,"unitPrice":242000,"amount":4356000}]'::jsonb,
     '발행 대기.', 'system-seed'),
  -- 옥션 낙찰 수수료(F084) — AUC-LIVE-01 낙찰(aw-live-01, co-0001) 5% 수수료
  ('inv-live-07','e-2026-live',NULL,'(주)한빛부스디자인','LIVE-2026-0007','auction_fee','aw-live-01',
     210000, 21000, 231000, 0, 'pending', CURRENT_DATE + 12, NULL, NULL,
     NULL, NULL,
     '[{"category":"AUCTION_FEE","description":"옥션 낙찰 수수료 5% (AUC-LIVE-01 · 낙찰 4,200,000원)","quantity":1,"unitPrice":210000,"amount":210000}]'::jsonb,
     '옥션 낙찰 수수료 청구(발행 대기).', 'system-seed'),
  -- 취소(환불 대상) — 계약금 납입 후 취소
  ('inv-live-08','e-2026-live',NULL,'넥스트이노베이션','LIVE-2026-0008','rental',NULL,
     6000000, 600000, 6600000, 2640000, 'cancelled', CURRENT_DATE + 9, now()-interval '16 day', NULL,
     now()-interval '2 day', '참가 철회(내부 사정) — 환불 규정 적용',
     '[{"category":"RENTAL","description":"부스 임대료 (18㎡ · 추가배정)","quantity":18,"unitPrice":333333,"amount":6000000}]'::jsonb,
     '취소 확정 — 환불 산정 대상.', 'system-seed')
ON CONFLICT (id) DO NOTHING;

-- 수납 기록(분납·완납·취소 전 계약금) --------------------------------------------
INSERT INTO invoice_payment (id, invoice_id, amount, method, memo, recorded_by, recorded_at) VALUES
  ('pay-live-01-1','inv-live-01', 2874960, 'transfer', '계약금 40%', 'system-seed', now()-interval '18 day'),
  ('pay-live-01-2','inv-live-01', 4312440, 'transfer', '잔금 60%',   'system-seed', now()-interval '5 day'),
  ('pay-live-03-1','inv-live-03', 4791600, 'transfer', '일시 완납',  'system-seed', now()-interval '3 day'),
  ('pay-live-02-1','inv-live-02', 2395800, 'transfer', '계약금 40%', 'system-seed', now()-interval '11 day'),
  ('pay-live-06-1','inv-live-06', 1916640, 'transfer', '계약금 40%', 'system-seed', now()-interval '5 day'),
  ('pay-live-08-1','inv-live-08', 2640000, 'transfer', '계약금 40%(취소 전 납입)', 'system-seed', now()-interval '13 day')
ON CONFLICT (id) DO NOTHING;

-- 세금계산서(F083) 2건 — 완납 청구(inv-live-01·inv-live-03) 기반 ----------------------
INSERT INTO tax_invoice (tenant_id, id, invoice_id, event_id, tax_invoice_no,
                         supplier_name, supplier_biz_no, supplier_ceo, supplier_addr,
                         buyer_name, supply_amount, vat, total, item_summary, status, issued_by) VALUES
  ('KINTEX','tax-live-0001','inv-live-01','e-2026-live','TAX-LIVE-0001',
     '킨텍스(KINTEX)','128-81-00000','대표이사','경기도 고양시 일산서구 킨텍스로 217',
     '(주)스마트오토메이션', 6534000, 653400, 7187400, '부스 임대료 (18㎡ · L-101)', 'issued', 'system-seed'),
  ('KINTEX','tax-live-0003','inv-live-03','e-2026-live','TAX-LIVE-0003',
     '킨텍스(KINTEX)','128-81-00000','대표이사','경기도 고양시 일산서구 킨텍스로 217',
     '글로벌테크', 4356000, 435600, 4791600, '부스 임대료 (18㎡ · L-103)', 'issued', 'system-seed')
ON CONFLICT (id) DO NOTHING;

-- 환불(F085) 1건 — 취소 청구 inv-live-08 기준. base=실납입(2,640,000), 개막 D-일 구간 환불율 -----
INSERT INTO invoice_refund (tenant_id, id, invoice_id, event_id, base_amount, refund_rate_percent,
                            refund_amount, forfeit_amount, days_before_event, bracket_label,
                            reason, ruleset_version, status, created_by) VALUES
  ('KINTEX','ref-live-0008','inv-live-08','e-2026-live', 2640000, 50.00,
     1320000, 1320000, 0, '개막일 이후 취소(50%)',
     '참가 철회 — 환불 규정(refund-v1.0) 구간 적용', 'refund-v1.0', 'recorded', 'system-seed')
ON CONFLICT (id) DO NOTHING;


-- ============================================================================
-- 2) 옥션 폐루프 — 옥션 2(낙찰 1·진행 1) + 초대 + 응찰 + 낙찰
-- ============================================================================
INSERT INTO auction (id, event_id, title, category, auction_type, award_criteria,
                     weight_price, weight_reputation, weight_delivery, round, deadline,
                     material_package_id, materials, accent, created_by) VALUES
  ('AUC-LIVE-01', 'e-2026-live', 'L-101 아일랜드 부스 장치공사', '전시디자인설치', 'reverse', 'comprehensive',
     60, 25, 15, 1, now() - interval '2 day', NULL, 'layout,design,boq', 'primary', 'demo-organizer'),
  ('AUC-LIVE-02', 'e-2026-live', '메인 통로 전기·조명 설치', '전기/조명', 'reverse', 'comprehensive',
     55, 25, 20, 1, now() + interval '3 day', NULL, 'layout,boq', 'success', 'demo-organizer')
ON CONFLICT (id) DO NOTHING;

INSERT INTO auction_invite (id, auction_id, company_id) VALUES
  ('ai-live-01-1', 'AUC-LIVE-01', 'co-0001'),
  ('ai-live-01-2', 'AUC-LIVE-01', 'co-0002'),
  ('ai-live-01-3', 'AUC-LIVE-01', 'co-0005'),
  ('ai-live-02-1', 'AUC-LIVE-02', 'co-0003'),
  ('ai-live-02-2', 'AUC-LIVE-02', 'co-0006'),
  ('ai-live-02-3', 'AUC-LIVE-02', 'co-0001')
ON CONFLICT (auction_id, company_id) DO NOTHING;

-- 응찰(견적) — (auction,company) 당 1행. AUC-LIVE-01 은 마감(낙찰), AUC-LIVE-02 는 진행 중.
INSERT INTO bid (id, auction_id, company_id, round, subtotal, vat, total, lead_days) VALUES
  ('bid-live-01-1', 'AUC-LIVE-01', 'co-0001', 1, 4200000, 420000, 4200000, 8),
  ('bid-live-01-2', 'AUC-LIVE-01', 'co-0002', 1, 4550000, 455000, 4550000, 7),
  ('bid-live-01-3', 'AUC-LIVE-01', 'co-0005', 1, 4380000, 438000, 4380000, 10),
  ('bid-live-02-1', 'AUC-LIVE-02', 'co-0003', 1, 3800000, 380000, 3800000, 6),
  ('bid-live-02-2', 'AUC-LIVE-02', 'co-0006', 1, 3650000, 365000, 3650000, 9)
ON CONFLICT (auction_id, company_id) DO NOTHING;

-- 낙찰(award) — AUC-LIVE-01 → co-0001 최저·종합 우수(수수료 청구 inv-live-07 source_ref 연동)
INSERT INTO award (id, auction_id, bid_id, reason, awarded_by, awarded_at) VALUES
  ('aw-live-01', 'AUC-LIVE-01', 'bid-live-01-1',
     '종합평가 1위(가격 60·평판 25·납기 15) — 최저 응찰가 및 납기 준수 이력 우수.', 'demo-organizer', now()-interval '1 day')
ON CONFLICT (auction_id) DO NOTHING;


-- ============================================================================
-- 3) 관람객·리드 폐루프 — 사전등록(체크인 분포) + 부스 리드(핫리드 포함)
-- ============================================================================
-- checkin_at 은 CURRENT_DATE 기준 상대(now()) — 재배포 시점의 '오늘' 체크인으로 집계(홈 KPI).
INSERT INTO visitor_registration
    (id, event_id, name, phone, email, company, visitor_type, agree_privacy, agree_marketing,
     badge_code, badge_issued, checkin_state, qr_token, checkin_at, registered_at) VALUES
  ('vr-live-101','e-2026-live','홍길동','010-0000-3101','livevis101@kintex.test','(주)스마트오토메이션','buyer',  true,true, 'KTX-L-0101',true, 'done',   'QR-LIVE0000000000000101', now()-interval '3 hour',  now()-interval '2 day'),
  ('vr-live-102','e-2026-live','김철수','010-0000-3102','livevis102@kintex.test','델타로보틱스',        'visitor',true,true, 'KTX-L-0102',true, 'done',   'QR-LIVE0000000000000102', now()-interval '2 hour',  now()-interval '2 day'),
  ('vr-live-103','e-2026-live','이영희','010-0000-3103','livevis103@kintex.test','한국센서테크',        'vip',    true,false,'KTX-L-0103',true, 'done',   'QR-LIVE0000000000000103', now()-interval '90 minute', now()-interval '1 day'),
  ('vr-live-104','e-2026-live','박민수','010-0000-3104','livevis104@kintex.test',NULL,                  'visitor',true,true, 'KTX-L-0104',true, 'done',   'QR-LIVE0000000000000104', now()-interval '40 minute', now()-interval '1 day'),
  ('vr-live-105','e-2026-live','최지우','010-0000-3105','livevis105@kintex.test','글로벌테크',          'buyer',  true,true, 'KTX-L-0105',true, 'waiting','QR-LIVE0000000000000105', NULL, now()-interval '20 hour'),
  ('vr-live-106','e-2026-live','정하늘','010-0000-3106','livevis106@kintex.test','미래제조연구소',      'visitor',true,false,'KTX-L-0106',false,'waiting','QR-LIVE0000000000000106', NULL, now()-interval '6 hour'),
  ('vr-live-107','e-2026-live','강보람','010-0000-3107','livevis107@kintex.test','바이오헬스랩',        'buyer',  true,true, 'KTX-L-0107',true, 'done',   'QR-LIVE0000000000000107', now()-interval '25 minute', now()-interval '5 hour')
ON CONFLICT (id) DO NOTHING;

-- 리드(SCR-32) — 부스 스코프 + demo-exhibitor 수집. 핫리드(score>=80) 2건 포함.
INSERT INTO lead
    (id, event_id, booth_id, exhibitor_id, name, phone, email, role, company, product,
     interest, score, ai_reasons, activity, followup_draft, ai_generated, collected_at) VALUES
  ('ld-live-001','e-2026-live','booth-live-02','demo-exhibitor','홍길동','010-0000-4001','lead001@kintex.test','생산기술 팀장','(주)스마트오토메이션','스마트 물류 AMR',5,92,
     '["부스 체류 20분(평균 대비 320%)","사양서 다운로드 3회","구매 결정권자 직급"]'::jsonb,
     '[{"text":"AMR 시연 참관","at":"오늘 13:40"},{"text":"견적 요청 폼 제출","at":"오늘 13:55"}]'::jsonb,
     '안녕하세요, 홍 팀장님. 스마트 물류 AMR 커스텀 제안서를 준비했습니다. 다음 주 미팅 가능하실까요?', true, now()-interval '4 hour'),
  ('ld-live-002','e-2026-live','booth-live-01','demo-exhibitor','김철수','010-0000-4002','lead002@kintex.test','구매 담당','델타로보틱스','AI 비전 검사 모듈',5,85,
     '["AI 비전 데모 2회 재방문","경쟁사 대비 견적 문의","도입 시기 명확(Q4)"]'::jsonb,
     '[{"text":"AI 비전 모듈 상담","at":"오늘 11:20"}]'::jsonb,
     '안녕하세요, 김 님. 요청하신 AI 비전 검사 모듈 견적서와 파일럿 프로그램 안내드립니다.', true, now()-interval '6 hour'),
  ('ld-live-003','e-2026-live','booth-live-03','demo-exhibitor','이영희','010-0000-4003','lead003@kintex.test','기술 기획','글로벌테크','협동로봇 HR-A1',3,64,
     '["협동로봇 세션 참석","브로슈어 다운로드"]'::jsonb,
     '[{"text":"데모 영상 시청","at":"오늘 10:10"}]'::jsonb,
     '안녕하세요, 이 님. 협동로봇 HR-A1 도입 사례집을 보내드립니다.', true, now()-interval '8 hour'),
  ('ld-live-004','e-2026-live','booth-live-06','demo-exhibitor','박민수','010-0000-4004','lead004@kintex.test','인프라 엔지니어','한국센서테크','클라우드 모니터링',2,43,
     '["짧은 부스 체류","자료 열람 없음"]'::jsonb,
     '[{"text":"부스 QR 스캔","at":"오늘 09:50"}]'::jsonb,
     '안녕하세요, 박 님. 클라우드 모니터링 소개 자료를 보내드립니다.', true, now()-interval '9 hour'),
  ('ld-live-005','e-2026-live','booth-live-02','demo-exhibitor','최지우','010-0000-4005','lead005@kintex.test','설비 담당','미래제조연구소','스마트팩토리 MES',4,71,
     '["MES 상담 15분","도입 예산 문의"]'::jsonb,
     '[{"text":"MES 상담","at":"오늘 12:05"}]'::jsonb,
     '안녕하세요, 최 님. 스마트팩토리 MES 데모 환경 안내드립니다.', true, now()-interval '5 hour'),
  ('ld-live-006','e-2026-live','booth-live-01','demo-exhibitor','정하늘','010-0000-4006','lead006@kintex.test','R&D','바이오헬스랩','바이오 계측 센서',3,58,
     '["센서 데모 관람","카탈로그 열람"]'::jsonb,
     '[{"text":"센서 데모","at":"오늘 14:20"}]'::jsonb,
     '안녕하세요, 정 님. 바이오 계측 센서 카탈로그와 견적 가이드를 보내드립니다.', true, now()-interval '2 hour')
ON CONFLICT (id) DO NOTHING;


-- ============================================================================
-- 4) 마케팅 폐루프 — EDM 캠페인 + 스폰서십 패키지/스폰서
-- ============================================================================
INSERT INTO edm_campaign (id, event_id, name, status, audience, meta, open_rate, click_rate) VALUES
  ('cp-live-001','e-2026-live','스마트 물류·자동화 코리아 개막 안내','done',      5400, '발송 완료: 1일 전', '48.2%', '12.6%'),
  ('cp-live-002','e-2026-live','VIP 바이어 상담회 초대','scheduled',               1200, '발송 예정: 오늘 18:00', '-',    '-'),
  ('cp-live-003','e-2026-live','현장 등록 관람객 만족도 설문','draft',              3100, '최종 수정: 2시간 전', '-',    '-')
ON CONFLICT (id) DO NOTHING;

INSERT INTO sponsorship_package (id, event_id, code, name, name_ko, price, accent, benefits, total_qty, sold_qty, dday, sort_order) VALUES
  ('sp-live-dia','e-2026-live','diamond','DIAMOND','다이아몬드', 30000000, 'primary',
     '["메인 배너 노출","기조연설 세션","VIP 라운지 부스","공식 도록 전면 광고"]'::jsonb, 2, 1, 3, 0),
  ('sp-live-gld','e-2026-live','gold','GOLD','골드', 15000000, 'warning',
     '["로비 배너","세션 슬롯 1","도록 반면 광고"]'::jsonb, 4, 2, 3, 1),
  ('sp-live-slv','e-2026-live','silver','SILVER','실버', 7000000, 'muted',
     '["디지털 사이니지 노출","도록 로고 게재"]'::jsonb, 6, 3, 3, 2)
ON CONFLICT (id) DO NOTHING;

INSERT INTO sponsorship_sponsor (id, event_id, package_id, name, tier_label, contract_status, fulfillment) VALUES
  ('ss-live-001','e-2026-live','sp-live-dia','(주)스마트오토메이션','DIAMOND','signed',
     '[{"item":"메인 배너","done":true},{"item":"기조연설","done":false}]'::jsonb),
  ('ss-live-002','e-2026-live','sp-live-gld','델타로보틱스','GOLD','signed',
     '[{"item":"로비 배너","done":true}]'::jsonb),
  ('ss-live-003','e-2026-live','sp-live-slv','한국센서테크','SILVER','pending',
     '[]'::jsonb)
ON CONFLICT (id) DO NOTHING;
