import { Inject, Injectable } from '@nestjs/common';
import { eq, type Db, skills } from '@mosaicstack/db';
import { DB } from '../database/database.module.js';

type Skill = typeof skills.$inferSelect;
type NewSkill = typeof skills.$inferInsert;

@Injectable()
export class SkillsService {
  constructor(@Inject(DB) private readonly db: Db) {}

  async findAll(): Promise<Skill[]> {
    return this.db.select().from(skills);
  }

  async findEnabled(): Promise<Skill[]> {
    return this.db.select().from(skills).where(eq(skills.enabled, true));
  }

  async findById(id: string): Promise<Skill | undefined> {
    const rows = await this.db.select().from(skills).where(eq(skills.id, id));
    return rows[0];
  }

  async findByName(name: string): Promise<Skill | undefined> {
    const rows = await this.db.select().from(skills).where(eq(skills.name, name));
    return rows[0];
  }

  async create(data: NewSkill): Promise<Skill> {
    const rows = await this.db.insert(skills).values(data).returning();
    return rows[0]!;
  }

  async update(id: string, data: Partial<NewSkill>): Promise<Skill | undefined> {
    const rows = await this.db
      .update(skills)
      .set({ ...data, updatedAt: new Date() })
      .where(eq(skills.id, id))
      .returning();
    return rows[0];
  }

  async remove(id: string): Promise<boolean> {
    const rows = await this.db.delete(skills).where(eq(skills.id, id)).returning();
    return rows.length > 0;
  }

  async toggle(id: string, enabled: boolean): Promise<Skill | undefined> {
    return this.update(id, { enabled });
  }
}
