import { query } from '../mysql';

export interface Tag {
  id: number;
  created_at: Date;
  modified_at: Date;
  tag: string;
}

export class TagModel {
  static async create(tag: Omit<Tag, 'id' | 'created_at' | 'modified_at'>): Promise<number> {
    const sql = 'INSERT INTO tag (tag) VALUES (?)';
    const params = [tag.tag];
    const result: any = await query(sql, params);
    return result.insertId;
  }

  static async getById(id: number): Promise<Tag | null> {
    const sql = 'SELECT * FROM tag WHERE id = ?';
    const params = [id];
    const rows: any = await query(sql, params);
    return rows.length > 0 ? rows[0] as Tag : null;
  }

  static async getByTag(tag: string): Promise<Tag | null> {
    const sql = 'SELECT * FROM tag WHERE tag = ?';
    const params = [tag];
    const rows: any = await query(sql, params);
    return rows.length > 0 ? rows[0] as Tag : null;
  }

  static async getAll(): Promise<Tag[]> {
    const sql = 'SELECT * FROM tag';
    const rows: any = await query(sql);
    return rows as Tag[];
  }

  static async update(id: number, tag: Partial<Omit<Tag, 'id' | 'created_at' | 'modified_at'>>): Promise<boolean> {
    const fields = Object.keys(tag);
    const values = Object.values(tag);

    if (fields.length === 0) {
      return false;
    }

    const sql = `UPDATE tag SET ${fields.map(field => `${field} = ?`).join(', ')} WHERE id = ?`;
    const params = [...values, id];
    const result: any = await query(sql, params);
    return result.affectedRows > 0;
  }

  static async delete(id: number): Promise<boolean> {
    const sql = 'DELETE FROM tag WHERE id = ?';
    const params = [id];
    const result: any = await query(sql, params);
    return result.affectedRows > 0;
  }
}
