// 자동 코드 생성 유틸리티

export interface AutoCodeFormat {
  id: string;
  codeType: "로트코드" | "자재번호";
  prefix: string;
  dateFormat: "YYMMDD" | "YYYYMMDD" | "YYMM" | "YY";
  sequenceDigits: number;
  separator: string;
  example: string;
  isActive: boolean;
  currentSequence: number;
}

// 기본 코드 형식 (localStorage에서 가져오거나 기본값 사용)
export const getDefaultCodeFormats = (): AutoCodeFormat[] => {
  const stored = localStorage.getItem('autoCodeFormats');
  if (stored) {
    try {
      return JSON.parse(stored);
    } catch {
      // JSON 파싱 실패 시 기본값 반환
    }
  }
  
  return [
    {
      id: "1",
      codeType: "로트코드",
      prefix: "LOT",
      dateFormat: "YYMMDD",
      sequenceDigits: 2,
      separator: "-",
      example: "LOT-241020-01",
      isActive: true,
      currentSequence: 0
    },
    {
      id: "2",
      codeType: "자재번호",
      prefix: "MAT",
      dateFormat: "YYMMDD",
      sequenceDigits: 2,
      separator: "-",
      example: "MAT-241020-01",
      isActive: true,
      currentSequence: 0
    }
  ];
};

// 코드 형식 저장
export const saveCodeFormats = (formats: AutoCodeFormat[]) => {
  localStorage.setItem('autoCodeFormats', JSON.stringify(formats));
};

// 날짜 문자열 생성
const getDateString = (dateFormat: AutoCodeFormat['dateFormat']): string => {
  const today = new Date();
  
  switch (dateFormat) {
    case "YYMMDD":
      return `${String(today.getFullYear()).slice(-2)}${String(today.getMonth() + 1).padStart(2, '0')}${String(today.getDate()).padStart(2, '0')}`;
    case "YYYYMMDD":
      return `${today.getFullYear()}${String(today.getMonth() + 1).padStart(2, '0')}${String(today.getDate()).padStart(2, '0')}`;
    case "YYMM":
      return `${String(today.getFullYear()).slice(-2)}${String(today.getMonth() + 1).padStart(2, '0')}`;
    case "YY":
      return String(today.getFullYear()).slice(-2);
    default:
      return "";
  }
};

// 자동 코드 생성
export const generateAutoCode = (
  codeType: "로트코드" | "자재번호",
  formats?: AutoCodeFormat[]
): string => {
  const codeFormats = formats || getDefaultCodeFormats();
  const format = codeFormats.find(f => f.codeType === codeType && f.isActive);
  
  if (!format) {
    // 기본 형식 사용
    const today = new Date();
    const dateStr = `${String(today.getFullYear()).slice(-2)}${String(today.getMonth() + 1).padStart(2, '0')}${String(today.getDate()).padStart(2, '0')}`;
    const prefix = codeType === "로트코드" ? "LOT" : "MAT";
    return `${prefix}-${dateStr}-01`;
  }
  
  const dateStr = getDateString(format.dateFormat);
  const sequence = String(format.currentSequence + 1).padStart(format.sequenceDigits, '0');
  
  // 순번 증가 및 저장
  const updatedFormats = codeFormats.map(f => 
    f.id === format.id 
      ? { ...f, currentSequence: f.currentSequence + 1 }
      : f
  );
  saveCodeFormats(updatedFormats);
  
  return `${format.prefix}${format.separator}${dateStr}${format.separator}${sequence}`;
};

// 당일 순번 초기화 (매일 자정에 실행해야 함)
export const resetDailySequence = () => {
  const formats = getDefaultCodeFormats();
  const resetFormats = formats.map(f => ({ ...f, currentSequence: 0 }));
  saveCodeFormats(resetFormats);
};

// 마지막 초기화 날짜 확인 및 필요 시 초기화
export const checkAndResetSequence = () => {
  const lastReset = localStorage.getItem('lastSequenceReset');
  const today = new Date().toDateString();
  
  if (lastReset !== today) {
    resetDailySequence();
    localStorage.setItem('lastSequenceReset', today);
  }
};
