import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';

@Injectable()
export class SkillsService {
  constructor(private prisma: PrismaService) {}

  private parseTags(tags: string): string[] {
    if (!tags) return [];
    try {
      const parsed = JSON.parse(tags);
      return Array.isArray(parsed) ? parsed : [];
    } catch {
      return tags.split(',').map(t => t.trim()).filter(Boolean);
    }
  }

  async findAll(params: { category?: string; difficulty?: string; search?: string; tag?: string }) {
    const where: any = { status: 'ACTIVE' };
    if (params.category) where.category = params.category;
    if (params.difficulty) where.difficulty = params.difficulty;
    if (params.search) {
      const q = params.search;
      where.OR = [
        { name: { contains: q } },
        { description: { contains: q } },
        { tags: { contains: q } },
      ];
    }
    if (params.tag) where.tags = { contains: params.tag };

    const items = await this.prisma.skill.findMany({
      where,
      orderBy: { sortOrder: 'asc' },
    });

    return {
      items: items.map(s => ({
        ...s,
        starters: JSON.parse(s.starters),
        tasks: JSON.parse(s.tasks),
        tags: this.parseTags(s.tags),
      })),
      total: items.length,
    };
  }

  async findById(id: string, userId?: number) {
    const skill = await this.prisma.skill.findUnique({ where: { id } });
    if (!skill) return null;

    let purchased = false;
    if (userId && skill.price) {
      const record = await this.prisma.userSkill.findUnique({
        where: { userId_skillId: { userId, skillId: id } },
      });
      purchased = !!record;
    }

    return {
      ...skill,
      starters: JSON.parse(skill.starters),
      tasks: JSON.parse(skill.tasks),
      tags: this.parseTags(skill.tags),
      purchased,
      locked: !purchased && !!skill.price,
    };
  }

  async getMarketplace(userId?: number) {
    const skills = await this.prisma.skill.findMany({
      where: { status: 'ACTIVE' },
      orderBy: { sortOrder: 'asc' },
    });

    let purchasedSet = new Set<string>();
    if (userId) {
      const records = await this.prisma.userSkill.findMany({
        where: { userId },
        select: { skillId: true },
      });
      purchasedSet = new Set(records.map(r => r.skillId));
    }

    return skills.map(s => ({
      id: s.id,
      name: s.name,
      description: s.description,
      icon: s.icon,
      category: s.category,
      difficulty: s.difficulty,
      tags: this.parseTags(s.tags),
      price: s.price,
      sortOrder: s.sortOrder,
      purchased: purchasedSet.has(s.id),
    }));
  }

  async getCategories() {
    const cats = await this.prisma.skill.findMany({
      where: { status: 'ACTIVE' },
      select: { category: true },
      distinct: ['category'],
      orderBy: { sortOrder: 'asc' },
    });
    const labels: Record<string, string> = { basic: '基础', technical: '技术', creative: '创意', education: '教育', advanced: '进阶', career: '职业', marketing: '营销', business: '商业' };
    return cats.map(c => ({ id: c.category, name: labels[c.category] || c.category }));
  }

  async getDifficulties() {
    return [
      { id: 'beginner', name: '入门' },
      { id: 'intermediate', name: '中级' },
      { id: 'advanced', name: '高级' },
    ];
  }
}
