/*
 * M15 공사/장치 옥션 실 API 클라이언트 (SCR-26·27·29·38).
 * 공용 클라이언트(../../api/client)만 사용 — client.ts·endpoints.ts·types.ts 무수정.
 * 정본: 백엔드 com.zioinfo.kintex.auction (AuctionController·ContractorController) 시그니처.
 *
 * ★ 봉인 입찰 보안은 서버가 강제한다:
 *   - 상세(GET /{id})는 마감 전 타사 입찰가·업체명을 미반환(ranking 행의 priceMasked=true·price=null).
 *   - 전체 견적 비교(award-view)는 마감 후 발주자에게만 200, 그 외 403.
 *   프론트는 서버가 준 값만 렌더한다(클라이언트에서 임의 언마스킹 없음).
 */
import { api } from '../../api/client';

export type AuctionType = '역경매' | 'RFQ';
export type AuctionStatus = '진행중' | '마감' | '정산중';
export type AwardCriteria = 'lowest' | 'comprehensive';
export type MaterialKind = 'layout' | 'design' | 'boq' | 'aiimage';

export interface AuctionSummary {
  id: string;
  eventId: string;
  title: string;
  category: string;
  type: AuctionType;
  status: AuctionStatus;
  round: number;
  dday: number;
  bidderCount: number;
  lowestPrice: number | null;
  awardedCompany: string | null;
  finalPrice: number | null;
  materials: MaterialKind[];
  accent: string; // primary | secondary | tertiary
}

export interface Weights {
  price: number;
  reputation: number;
  delivery: number;
}

export interface MaterialPackage {
  layoutUrl: string | null;
  designUrl: string | null;
  boqUrl: string | null;
  aiImageUrl: string | null;
}

/** 봉인 순위 행 — priceMasked=true 이면 price 는 null(타사 비공개). */
export interface RankRow {
  rank: number;
  alias: string;
  isMe: boolean;
  isLowest: boolean;
  priceMasked: boolean;
  price: number | null;
}

export interface AuctionDetail {
  id: string;
  eventId: string;
  title: string;
  category: string;
  type: AuctionType;
  status: AuctionStatus;
  round: number;
  dday: number;
  deadline: string;
  bidderCount: number;
  lowestPrice: number | null;
  awardCriteria: AwardCriteria;
  weights: Weights;
  materials: MaterialKind[];
  materialPackage: MaterialPackage;
  sealed: boolean;
  myRank: number | null;
  myPrice: number | null;
  ranking: RankRow[];
  canBid: boolean;
  canViewAward: boolean;
  awardedCompany: string | null;
  finalPrice: number | null;
}

export interface BidResult {
  id: string;
  round: number;
  subtotal: number;
  vat: number;
  total: number; // 경쟁 순위 금액(부가세 별도)
  grandTotal: number; // 부가세 포함 총액
  version: number;
  myRank: number | null;
  lowestPrice: number | null;
}

export interface QuoteLine {
  trade: string;
  material: string;
  qty: number;
  unitPrice: number;
}

export interface Quote {
  bidId: string;
  companyId: string;
  alias: string;
  subtitle: string;
  recommended: boolean;
  totalPrice: number;
  priceDeltaPct: number;
  isLowestPrice: boolean;
  leadDays: number;
  isShortestLead: boolean;
  reputation: number;
  score: number;
}

export interface RiskBar {
  label: string;
  pct: number;
  tone: 'success' | 'ai' | 'warn';
}

export interface AwardResult {
  id: string;
  bidId: string;
  companyName: string | null;
  awardedAt: string | null;
}

export interface AwardView {
  auctionId: string;
  auctionTitle: string;
  bidderCount: number;
  awardCriteria: AwardCriteria;
  weights: Weights;
  quotes: Quote[];
  riskBars: RiskBar[];
  awarded: AwardResult | null;
}

// ── 업체 포털 대시보드(SCR-38) ──
export interface Kpi {
  label: string;
  value: number;
  tone: 'normal' | 'success' | 'error';
}
export interface AwardedBooth {
  auctionId: string;
  event: string;
  name: string;
  booth: string;
  client: string | null;
  dday: number | null;
  stage: string;
}
export interface MyBid {
  auctionId: string;
  auctionTitle: string;
  myPrice: number;
  myRank: number | null;
  dday: number;
}
export interface FeedItem {
  text: string;
  meta: string;
  tone: 'ok' | 'warn' | 'info';
}
export interface ContractorDashboard {
  companyName: string | null;
  kpis: Kpi[];
  awardedBooths: AwardedBooth[];
  myAuctionBids: MyBid[];
  feed: FeedItem[];
}

export interface CreateAuctionBody {
  eventId: string;
  title: string;
  category: string;
  type: AuctionType;
  awardCriteria: AwardCriteria;
  weights: Weights;
  round: number;
  deadline: string;
  materialPackageId?: string | null;
  materials: MaterialKind[];
  invitedCompanyIds: string[];
}

export interface BidBody {
  total?: number; // 라인아이템 미전송 시 경쟁 금액(부가세 별도)
  leadDays?: number;
  validUntil?: string | null;
  terms?: string | null;
  lines?: QuoteLine[];
}

export interface AwardBody {
  bidId: string;
  reason: string;
}

/** F035 물량서(BOQ) 라인 — 공종·품명·단위·수량·산출근거(금액 미포함). */
export interface BoqLine {
  seq: number;
  trade: string;
  item: string;
  unit: string;
  qty: number;
  basis: string;
}

/** F035 물량서(BOQ) 자동산출 결과 — 서버 규칙 기반 집계(부스 설계 M2/M4 읽기). */
export interface BoqResult {
  auctionId: string;
  eventId: string;
  scope: 'booth' | 'event';
  scopeLabel: string;
  boothCount: number;
  totalAreaM2: number;
  lines: BoqLine[];
  note: string;
  generatedAt: string;
}

export const MATERIAL_LABEL: Record<MaterialKind, string> = {
  layout: '배치',
  design: '설계',
  boq: '물량서',
  aiimage: '예상이미지',
};

/** 원 금액 → ₩ 구분자 포맷. */
export function formatWon(v: number): string {
  return `₩${v.toLocaleString('ko-KR')}`;
}

export const auctionApi = {
  list: (eventId?: string) =>
    api.get<AuctionSummary[]>(`/api/auctions${eventId ? `?eventId=${encodeURIComponent(eventId)}` : ''}`),
  detail: (id: string) => api.get<AuctionDetail>(`/api/auctions/${encodeURIComponent(id)}`),
  create: (body: CreateAuctionBody) => api.post<AuctionSummary>('/api/auctions', body),
  bid: (id: string, body: BidBody) => api.post<BidResult>(`/api/auctions/${encodeURIComponent(id)}/bids`, body),
  close: (id: string) => api.post<AuctionSummary>(`/api/auctions/${encodeURIComponent(id)}/close`),
  award: (id: string, body: AwardBody) => api.post<AwardResult>(`/api/auctions/${encodeURIComponent(id)}/award`, body),
  awardView: (id: string) => api.get<AwardView>(`/api/auctions/${encodeURIComponent(id)}/award-view`),
  boq: (id: string) => api.get<BoqResult>(`/api/auctions/${encodeURIComponent(id)}/boq`),
};

export const contractorApi = {
  dashboard: () => api.get<ContractorDashboard>('/api/contractor/dashboard'),
};
