import { AppDataSource } from '../config/database';
import { BlogPost, BlogPostStatus, BlogPostCategory } from '../models/BlogPost';
import { ILike } from 'typeorm';

const blogRepo = () => AppDataSource.getRepository(BlogPost);

export class BlogService {
  // ==========================================
  // PUBLIC
  // ==========================================

  /**
   * Get published posts with optional filters (public, paginated)
   */
  static async getPosts(
    category?: BlogPostCategory,
    page: number = 1,
    limit: number = 10,
    search?: string,
  ) {
    const offset = (page - 1) * limit;

    const qb = blogRepo()
      .createQueryBuilder('post')
      .leftJoinAndSelect('post.author', 'author')
      .where('post.status = :status', { status: 'published' });

    if (category) {
      qb.andWhere('post.category = :category', { category });
    }

    if (search) {
      qb.andWhere(
        '(post.title ILIKE :search OR post.excerpt ILIKE :search OR post.content ILIKE :search)',
        { search: `%${search}%` },
      );
    }

    qb.orderBy('post.published_at', 'DESC')
      .skip(offset)
      .take(limit);

    const [posts, total] = await qb.getManyAndCount();

    return {
      posts: posts.map(p => ({
        id: p.id,
        title: p.title,
        excerpt: p.excerpt,
        slug: p.slug,
        category: p.category,
        cover_image_url: p.cover_image_url,
        view_count: p.view_count,
        published_at: p.published_at,
        author: p.author ? { id: p.author.id, username: p.author.username, profile_image_url: p.author.profile_image_url } : null,
      })),
      total,
      page,
      pages: Math.ceil(total / limit),
    };
  }

  /**
   * Get single post by ID (public) — increments view count
   */
  static async getPost(id: string) {
    const post = await blogRepo().findOne({
      where: { id, status: 'published' },
      relations: ['author'],
    });
    if (!post) throw new Error('Article introuvable');

    // Increment view count
    post.view_count += 1;
    await blogRepo().save(post);

    return {
      ...post,
      author: post.author ? { id: post.author.id, username: post.author.username, profile_image_url: post.author.profile_image_url } : null,
    };
  }

  /**
   * Get single post by slug (public) — increments view count
   */
  static async getPostBySlug(slug: string) {
    const post = await blogRepo().findOne({
      where: { slug, status: 'published' },
      relations: ['author'],
    });
    if (!post) throw new Error('Article introuvable');

    // Increment view count
    post.view_count += 1;
    await blogRepo().save(post);

    return {
      ...post,
      author: post.author ? { id: post.author.id, username: post.author.username, profile_image_url: post.author.profile_image_url } : null,
    };
  }

  /**
   * Get distinct categories from published posts
   */
  static async getCategories() {
    const result = await blogRepo()
      .createQueryBuilder('post')
      .select('DISTINCT post.category', 'category')
      .where('post.status = :status', { status: 'published' })
      .getRawMany();

    return result.map(r => r.category as BlogPostCategory);
  }

  // ==========================================
  // ADMIN
  // ==========================================

  /**
   * Get all posts (admin, paginated)
   */
  static async getAllPosts(page: number = 1, limit: number = 20) {
    const offset = (page - 1) * limit;
    const [posts, total] = await blogRepo().findAndCount({
      relations: ['author'],
      order: { created_at: 'DESC' },
      skip: offset,
      take: limit,
    });
    return { posts, total, page, pages: Math.ceil(total / limit) };
  }

  /**
   * Create a new blog post (admin)
   */
  static async createPost(authorId: string, data: {
    title: string;
    content: string;
    category?: BlogPostCategory;
    excerpt?: string;
    cover_image_url?: string;
    status?: BlogPostStatus;
    slug?: string;
  }) {
    if (!data.title?.trim() || !data.content?.trim()) {
      throw new Error('Titre et contenu requis');
    }

    // Generate slug from title if not provided
    const slug = data.slug || BlogService.generateSlug(data.title);

    // Check slug uniqueness
    const existing = await blogRepo().findOneBy({ slug });
    if (existing) throw new Error('Ce slug existe d\u00e9j\u00e0');

    const post = blogRepo().create({
      author_id: authorId,
      title: data.title.trim(),
      content: data.content.trim(),
      excerpt: data.excerpt?.trim() || null,
      cover_image_url: data.cover_image_url || null,
      category: data.category || 'blog',
      slug,
      status: data.status || 'draft',
      published_at: data.status === 'published' ? new Date() : null,
    });

    return blogRepo().save(post);
  }

  /**
   * Update a blog post (admin)
   */
  static async updatePost(id: string, data: Partial<{
    title: string;
    content: string;
    excerpt: string;
    cover_image_url: string;
    category: BlogPostCategory;
    status: BlogPostStatus;
    slug: string;
  }>) {
    const post = await blogRepo().findOneBy({ id });
    if (!post) throw new Error('Article introuvable');

    if (data.title) post.title = data.title.trim();
    if (data.content) post.content = data.content.trim();
    if (data.excerpt !== undefined) post.excerpt = data.excerpt?.trim() || null;
    if (data.cover_image_url !== undefined) post.cover_image_url = data.cover_image_url || null;
    if (data.category) post.category = data.category;
    if (data.slug) {
      const existing = await blogRepo().findOneBy({ slug: data.slug });
      if (existing && existing.id !== id) throw new Error('Ce slug existe d\u00e9j\u00e0');
      post.slug = data.slug;
    }
    if (data.status) {
      if (data.status === 'published' && post.status !== 'published') {
        post.published_at = new Date();
      }
      post.status = data.status;
    }

    return blogRepo().save(post);
  }

  /**
   * Delete (archive) a blog post (admin)
   */
  static async deletePost(id: string) {
    const post = await blogRepo().findOneBy({ id });
    if (!post) throw new Error('Article introuvable');
    post.status = 'archived';
    return blogRepo().save(post);
  }

  // ==========================================
  // HELPERS
  // ==========================================

  /**
   * Generate URL-friendly slug from title
   */
  private static generateSlug(title: string): string {
    return title
      .toLowerCase()
      .normalize('NFD')
      .replace(/[\u0300-\u036f]/g, '') // remove accents
      .replace(/[^a-z0-9\s-]/g, '')
      .replace(/\s+/g, '-')
      .replace(/-+/g, '-')
      .substring(0, 180)
      + '-' + Date.now().toString(36);
  }
}
