import { createApi } from "@reduxjs/toolkit/query/react";
import baseQueryWithReauth from "./baseQuery";

/* ================= TYPES ================= */

export type CourseStatus =
  | "publish"
  | "unpublish"
  | "archive"
  | "processing"
  | "in_draft";

export interface GetCoursesParams {
  limit?: number;
  offset?: number;
  status?: CourseStatus;
  search_query?: string;
  course_category?: string[];
  price_range?: string;
  duration_range?: string;
  min_rating?: number;
  sort_by?: string;
}

export interface Course {
  id: string;
  course_name: string;
  course_desc: string;
  thumbnail_img: string;
  course_category_xid: string;
  course_category_name: string;
  best_value: number;
  avg_rating: number;
  total_reviews: number;
  retail_type: string;
  price: number;
  is_certificate_available: boolean;
  course_status: CourseStatus;
  updated_at: string;
  total_duration: number;
  no_of_modules: number;
}

export interface PaginationInfo {
  total_count: number;
  limit: number;
  offset: number;
  applied_filters: {
    status: string | null;
    course_category_xid: string[] | null;
    content_types_xid: string[] | null;
    search_query: string | null;
    price_range: string | null;
    duration_range: string | null;
    min_rating: number | null;
    sort_by: string | null;
  };
}

export interface CourseListResponse {
  success: boolean;
  status: number;
  message: string;
  data: {
    pagination_info: PaginationInfo;
    items: Course[];
  };
}

export interface CourseReview {
  id: string;
  rating: number;
  comment: string;
  video_url: string | null;
  reviewer_name: string;
  profile_image: string | null;
  bio: string | null;
  created_at: string;
}

export interface CourseFaq {
  id: string;
  question: string;
  answer: string;
}

export interface CourseTargetAudience {
  id: string;
  course_xid: string;
  course_icon_xid: string;
  title: string;
  description: string;
  display_order: number;
}

export interface CourseLearningOutcome {
  id: string;
  course_xid: string;
  title: string;
  description: string;
  display_order: number;
}

export interface CourseLearningStructure {
  id: string;
  course_xid: string;
  title: string;
  description: string;
  display_order: number;
}

export interface CourseFacultyCredential {
  id: string;
  course_xid: string;
  course_faculty_xid: string;
  credential_name: string;
  display_order: number;
}

export interface CourseFaculty {
  id: string;
  course_xid: string;
  faculty_name: string;
  faculty_title: string;
  faculty_organization_name: string;
  faculty_biography: string;
  display_order: number;
  expertises: string[] | null;
  credentials: CourseFacultyCredential[];
}

export interface CourseLessonResource {
  id: string;
  course_xid: string;
  module_xid: string;
  lesson_xid: string;
  content_xid: string;
  content_type_xid: string;
  content_title: string;
  total_duration: number | null;
  content_type_name: string;
  is_active: boolean;
}

export interface CourseLesson {
  id: string;
  course_xid: string;
  module_xid: string;
  lesson_title: string;
  lesson_description: string;
  is_lock_lesson: boolean;
  display_order: number;
  lesson_resources: CourseLessonResource[];
}

export interface CourseModule {
  id: string;
  course_xid: string;
  module_name: string;
  display_order: number;
  lessons: CourseLesson[];
}

export interface CourseResource {
  id: string;
  course_xid: string;
  content_xid: string;
  content_type_xid: string;
  display_order: number | null;
}

export interface CourseCertificateTemplate {
  id: string;
  template_name: string;
  template_code: string;
  display_order: number;
  is_active: boolean;
}

export interface CourseCertificate {
  id: string;
  course_xid: string;
  certificate_template_xid: string;
  company_logo_url: string | null;
  institution_name: string;
  program_title: string;
  signatory_name: string;
  signatory_title: string;
  digital_signature_url: string | null;
  minimum_pass_percentage: number;
  complete_all_lesson_required: boolean;
  certificate_template: CourseCertificateTemplate;
}

export interface RecommendedCourse {
  id: string;
  course_name: string;
  course_desc: string;
  thumbnail_img: string;
  price: string;
  best_value: number;
  duration: number;
  recommended_course_reviews: {
    id: string;
    rating: number;
    comment: string;
    reviewer_name: string;
  }[];
}

export interface CourseDetail {
  id: string;
  course_name: string;
  course_desc: string;
  thumbnail_img: string;
  course_category_xid: string;
  duration: number;
  retail_type: string;
  price: string | number;
  best_value: number;
  target_audience_desc: string | null;
  learning_outcomes_desc: string | null;
  learning_structure_desc: string | null;
  our_methodology_desc: string | null;
  is_certificate_available: boolean;
  course_status: CourseStatus;
  benefit_section: string | null;
  learning_section: string | null;
  structure_section: string | null;
  approach_section: string | null;
  faculty_section: string | null;
  avg_rating: number;
  total_reviews: number;
  reviews: CourseReview[];
  course_faqs: CourseFaq[];
  total_modules: number;
  total_lessons: number;
  formatted_duration: string;
  course_category_name: string;
  course_language_xids: string[];
  course_target_audiences: CourseTargetAudience[];
  course_learning_outcomes: CourseLearningOutcome[];
  course_learning_structures: CourseLearningStructure[];
  course_facilities: CourseFaculty[];
  modules: CourseModule[];
  course_resources: CourseResource[];
  course_certificate: CourseCertificate | null;
  recommended_courses: RecommendedCourse[];
}

export interface CourseDetailResponse {
  success: boolean;
  status: number;
  message: string;
  data: CourseDetail;
  errors: unknown;
  correlation_id: string;
}

/* ================= PREPOPULATE TYPES ================= */

export interface CourseCategory {
  id: string;
  category_name: string;
  category_code: string;
  display_order: number;
  is_active: boolean;
}

export interface GetCourseCategoriesParams {
  limit?: number;
  offset?: number;
  is_active?: boolean;
}

export interface CourseCategoriesResponse {
  success: boolean;
  status: number;
  message: string;
  data: {
    pagination_info: {
      total_count: number;
      limit: number;
      offset: number;
    };
    items: CourseCategory[];
  };
}

/* ================= API ================= */

export const courseApi = createApi({
  reducerPath: "courseApi",
  baseQuery: baseQueryWithReauth,
  tagTypes: ["Course", "CourseCategories"],
  endpoints: (builder) => ({
    // GET Courses
    getCourses: builder.query<CourseListResponse, GetCoursesParams | void>({
      query: (params) => {
        const searchParams = new URLSearchParams();

        if (params) {
          if (params.limit) searchParams.append("limit", params.limit.toString());
          if (params.offset) searchParams.append("offset", params.offset.toString());
          if (params.status) searchParams.append("status", params.status);
          if (params.search_query) searchParams.append("search_query", params.search_query);
          if (params.price_range) searchParams.append("price_range", params.price_range);
          if (params.duration_range) searchParams.append("duration_range", params.duration_range);
          if (params.min_rating !== undefined)
            searchParams.append("min_rating", params.min_rating.toString());
          if (params.sort_by) searchParams.append("sort_by", params.sort_by);

          // ✅ array support
          if (params.course_category?.length) {
            params.course_category.forEach((cat) => {
              searchParams.append("course_category", cat);
            });
          }
        }

        const queryString = searchParams.toString();

        return queryString
          ? `admin/course/public/list?${queryString}`
          : `admin/course/public/list`;
      },

      providesTags: (result) =>
        result
          ? [
              ...result.data.items.map(({ id }) => ({
                type: "Course" as const,
                id,
              })),
              { type: "Course", id: "LIST" },
            ]
          : [{ type: "Course", id: "LIST" }],
    }),

    // GET Course Categories (Prepopulate)
    getCourseCategories: builder.query<CourseCategoriesResponse, GetCourseCategoriesParams | void>({
      query: (params) => {
        const searchParams = new URLSearchParams();
        if (params) {
          if (params.limit) searchParams.append("limit", params.limit.toString());
          if (params.offset) searchParams.append("offset", params.offset.toString());
          if (params.is_active !== undefined) searchParams.append("is_active", params.is_active.toString());
        }
        const queryString = searchParams.toString();
        return queryString
          ? `admin/prepopulate/course-categories/list?${queryString}`
          : `admin/prepopulate/course-categories/list`;
      },
      providesTags: ["CourseCategories"],
    }),

    // GET Course By Id
    getcoursebyid: builder.query<CourseDetailResponse, string>({
      query: (course_id) => `admin/course/${course_id}`,
      providesTags: (_result, _error, course_id) => [{ type: "Course", id: course_id }],
    }),

    
  }),
});

export const {
  useGetCoursesQuery,
  useGetCourseCategoriesQuery,
  useGetcoursebyidQuery,
} = courseApi;
