import PocketBase from 'pocketbase';
import type { Post } from '../globalInterfaces';

const PB_URL = import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090';

export const pb = new PocketBase(PB_URL);

pb.collection('_superusers').authRefresh().catch(() => {});

export async function getPosts(options?: {
  page?: number;
  perPage?: number;
  category?: string;
  search?: string;
}): Promise<{ posts: Post[]; total: number; page: number; totalPages: number }> {
  const page = options?.page || 1;
  const perPage = options?.perPage || 10;

  const filter: string[] = ['draft = false'];

  if (options?.category && options.category !== 'Все') {
    filter.push(`category = "${options.category}"`);
  }

  if (options?.search) {
    filter.push(`(title ~ "${options.search}" || description ~ "${options.search}")`);
  }

  const result = await pb.collection('posts').getList(page, perPage, {
    filter: filter.join(' && '),
    sort: '-date',
  });

  return {
    posts: (result.items || []) as unknown as Post[],
    total: result.totalItems || 0,
    page: result.page || 1,
    totalPages: result.totalPages || 1,
  };
}

export async function getPostBySlug(slug: string): Promise<Post | null> {
  const result = await pb.collection('posts').getList(1, 1, {
    filter: `slug="${slug}" && draft = false`,
  });

  if (!result.items || result.totalItems === 0) {
    return null;
  }

  return result.items[0] as unknown as Post;
}

export async function getAllCategories(): Promise<string[]> {
  const result = await pb.collection('posts').getFullList({
    filter: 'draft = false',
    fields: 'category',
  });

  const categories = (result || []).map((post) => post.category as string).filter(Boolean);
  return ['Все', ...new Set(categories)];
}

export function getPostImageUrl(post: { image?: string }): string {
  if (post.image) {
    const fileUrl = pb.files.getUrl(post, post.image);
    if (fileUrl.startsWith('/')) {
      return `${PB_URL}${fileUrl}`;
    }
    return fileUrl;
  }
  return '/images/blog/default.avif';
}