import apiClient from './authApi';

export interface RequestSummary {
  summaryId: string;
  requestId: string;
  initiatorId: string;
  title: string;
  description: string | null;
  closingRemarks: string | null;
  isAiGenerated: boolean;
  conclusionId: string | null;
  createdAt: string;
  updatedAt: string;
}

export interface SharedSummary {
  sharedSummaryId: string;
  summaryId: string;
  requestId: string;
  requestNumber: string;
  title: string;
  initiatorName: string;
  sharedByName: string;
  sharedAt: string;
  viewedAt: string | null;
  isRead: boolean;
  closureDate: string | null;
}

export interface SummaryDetails {
  summaryId: string;
  requestId: string;
  requestNumber: string;
  title: string;
  description: string;
  closingRemarks: string;
  isAiGenerated: boolean;
  createdAt: string;
  initiator: {
    name: string;
    designation: string;
    department: string | null;
    email: string;
    status: string;
    timestamp: string;
    remarks: string;
  };
  approvers: Array<{
    levelNumber: number;
    levelName: string;
    name: string;
    designation: string;
    department: string | null;
    email: string;
    status: string;
    timestamp: string;
    remarks: string;
  }>;
  workflow: {
    priority: string;
    status: string;
    submissionDate: string | null;
    closureDate: string | null;
  };
}

/**
 * Create a summary for a closed request
 */
export async function createSummary(requestId: string): Promise<RequestSummary> {
  const res = await apiClient.post('/summaries', { requestId });
  return res.data.data;
}

/**
 * Get summary details
 */
export async function getSummaryDetails(summaryId: string): Promise<SummaryDetails> {
  const res = await apiClient.get(`/summaries/${summaryId}`);
  return res.data.data;
}

/**
 * Share summary with users
 */
export async function shareSummary(summaryId: string, userIds: string[]): Promise<SharedSummary[]> {
  const res = await apiClient.post(`/summaries/${summaryId}/share`, { userIds });
  return res.data.data;
}

/**
 * List summaries shared with current user
 */
export async function listSharedSummaries(params: { page?: number; limit?: number } = {}): Promise<{
  data: SharedSummary[];
  pagination: { page: number; limit: number; total: number; totalPages: number };
}> {
  const { page = 1, limit = 20 } = params;
  const res = await apiClient.get('/summaries/shared', { params: { page, limit } });
  return {
    data: res.data.data?.data || res.data.data || [],
    pagination: res.data.data?.pagination || { page, limit, total: 0, totalPages: 1 }
  };
}

/**
 * Mark shared summary as viewed
 */
export async function markAsViewed(sharedSummaryId: string): Promise<void> {
  await apiClient.patch(`/summaries/shared/${sharedSummaryId}/view`);
}

/**
 * List summaries created by current user
 */
export async function listMySummaries(params: { page?: number; limit?: number } = {}): Promise<{
  data: RequestSummary[];
  pagination: { page: number; limit: number; total: number; totalPages: number };
}> {
  const { page = 1, limit = 20 } = params;
  const res = await apiClient.get('/summaries/my', { params: { page, limit } });
  return {
    data: res.data.data?.data || res.data.data || [],
    pagination: res.data.data?.pagination || { page, limit, total: 0, totalPages: 1 }
  };
}

/**
 * Get summary by requestId (checks if summary exists without creating)
 * Returns null if summary doesn't exist
 */
export async function getSummaryByRequestId(requestId: string): Promise<RequestSummary | null> {
  try {
    const res = await apiClient.get(`/summaries/request/${requestId}`);
    return res.data.data;
  } catch (error: any) {
    // If summary doesn't exist (404), return null
    if (error?.response?.status === 404) {
      return null;
    }
    // For other errors, also return null
    return null;
  }
}

export interface SharedRecipient {
  userId: string;
  email: string;
  displayName: string;
  designation: string | null;
  department: string | null;
  sharedAt: string;
  viewedAt: string | null;
  isRead: boolean;
}

/**
 * Get list of users who received shared summary for a specific summary
 */
export async function getSharedRecipients(summaryId: string): Promise<SharedRecipient[]> {
  const res = await apiClient.get(`/summaries/${summaryId}/recipients`);
  return res.data.data || [];
}

