import { db } from './config';
import { 
  collection, 
  doc, 
  getDoc, 
  getDocs, 
  setDoc, 
  updateDoc, 
  query, 
  where,
  serverTimestamp,
  Timestamp
} from 'firebase/firestore';
import type { ProjectPhase, ProjectPhaseData, ProjectPhaseScores } from '@/lib/types/project-artifacts';

// Type definitions
export interface User {
  uid: string;
  email: string;
  displayName?: string;
  photoURL?: string;
  workspace: string; // e.g., "marks-account"
  createdAt: Timestamp;
  updatedAt: Timestamp;
}

export interface Project {
  id: string;
  name: string;
  slug: string;
  userId: string;
  workspace: string;
  productName: string;
  productVision?: string;
  isForClient: boolean;
  hasLogo: boolean;
  hasDomain: boolean;
  hasWebsite: boolean;
  hasGithub: boolean;
  hasChatGPT: boolean;
  githubRepo?: string;
  chatGPTProjectId?: string;
  currentPhase: ProjectPhase;
  phaseStatus: 'not_started' | 'in_progress' | 'completed';
  phaseData?: ProjectPhaseData;
  phaseHistory?: Array<Record<string, unknown>>;
  phaseScores?: ProjectPhaseScores;
  createdAt: Timestamp;
  updatedAt: Timestamp;
}

export interface Session {
  id: string;
  projectId?: string | null;
  userId: string;
  startTime: Timestamp;
  endTime?: Timestamp | null;
  duration?: number | null;
  workspacePath?: string | null;
  workspaceName?: string | null;
  tokensUsed: number;
  cost: number;
  model: string;
  filesModified?: string[];
  conversationSummary?: string | null;
  conversation?: Array<{
    role: string;
    content: string;
    timestamp: string | Date;
  }>;
  createdAt: Timestamp;
}

export interface Analysis {
  id: string;
  projectId: string;
  type: 'code' | 'chatgpt' | 'github' | 'combined';
  summary: string;
  techStack?: string[];
  features?: string[];
  rawData?: any;
  createdAt: Timestamp;
}

// User operations
export async function createUser(uid: string, data: Partial<User>) {
  const userRef = doc(db, 'users', uid);
  await setDoc(userRef, {
    uid,
    ...data,
    createdAt: serverTimestamp(),
    updatedAt: serverTimestamp(),
  });
}

export async function getUser(uid: string): Promise<User | null> {
  const userRef = doc(db, 'users', uid);
  const userSnap = await getDoc(userRef);
  return userSnap.exists() ? (userSnap.data() as User) : null;
}

// Project operations
export async function createProject(projectData: Omit<Project, 'id' | 'createdAt' | 'updatedAt'>) {
  const projectRef = doc(collection(db, 'projects'));
  await setDoc(projectRef, {
    ...projectData,
    id: projectRef.id,
    createdAt: serverTimestamp(),
    updatedAt: serverTimestamp(),
  });
  return projectRef.id;
}

export async function getProject(projectId: string): Promise<Project | null> {
  const projectRef = doc(db, 'projects', projectId);
  const projectSnap = await getDoc(projectRef);
  return projectSnap.exists() ? (projectSnap.data() as Project) : null;
}

export async function getUserProjects(userId: string): Promise<Project[]> {
  const q = query(collection(db, 'projects'), where('userId', '==', userId));
  const querySnapshot = await getDocs(q);
  return querySnapshot.docs.map(doc => doc.data() as Project);
}

export async function updateProject(projectId: string, data: Partial<Project>) {
  const projectRef = doc(db, 'projects', projectId);
  await updateDoc(projectRef, {
    ...data,
    updatedAt: serverTimestamp(),
  });
}

// Session operations
export async function createSession(sessionData: Omit<Session, 'id' | 'createdAt'>) {
  const sessionRef = doc(collection(db, 'sessions'));
  await setDoc(sessionRef, {
    ...sessionData,
    id: sessionRef.id,
    createdAt: serverTimestamp(),
  });
  return sessionRef.id;
}

export async function getProjectSessions(projectId: string): Promise<Session[]> {
  const q = query(collection(db, 'sessions'), where('projectId', '==', projectId));
  const querySnapshot = await getDocs(q);
  return querySnapshot.docs.map(doc => doc.data() as Session);
}

// Analysis operations
export async function createAnalysis(analysisData: Omit<Analysis, 'id' | 'createdAt'>) {
  const analysisRef = doc(collection(db, 'analyses'));
  await setDoc(analysisRef, {
    ...analysisData,
    id: analysisRef.id,
    createdAt: serverTimestamp(),
  });
  return analysisRef.id;
}

export async function getProjectAnalyses(projectId: string): Promise<Analysis[]> {
  const q = query(collection(db, 'analyses'), where('projectId', '==', projectId));
  const querySnapshot = await getDocs(q);
  return querySnapshot.docs.map(doc => doc.data() as Analysis);
}

