const { v4: uuidv4 } = require('uuid');
const database = require('../config/database');

class CommitDetailsModel {
  constructor() {
    this.db = database;
  }

  async createCommitDetail(commitData) {
    const {
      repository_id,
      commit_sha,
      author_name,
      author_email,
      message,
      url,
      committed_at
    } = commitData;

    const query = `
      INSERT INTO repository_commit_details (
        id, repository_id, commit_sha, author_name, author_email, 
        message, url, committed_at, created_at
      ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW())
      ON CONFLICT (repository_id, commit_sha) 
      DO UPDATE SET
        author_name = EXCLUDED.author_name,
        author_email = EXCLUDED.author_email,
        message = EXCLUDED.message,
        url = EXCLUDED.url,
        committed_at = EXCLUDED.committed_at
      RETURNING *
    `;

    const values = [
      uuidv4(),
      repository_id,
      commit_sha,
      author_name,
      author_email,
      message,
      url,
      committed_at || new Date()
    ];

    const result = await this.db.query(query, values);
    return result.rows[0];
  }

  async getCommitsByRepository(repository_id, limit = 50, offset = 0) {
    const query = `
      SELECT * FROM repository_commit_details 
      WHERE repository_id = $1 
      ORDER BY committed_at DESC 
      LIMIT $2 OFFSET $3
    `;
    
    const result = await this.db.query(query, [repository_id, limit, offset]);
    return result.rows;
  }

  async getCommitBySha(repository_id, commit_sha) {
    const query = `
      SELECT * FROM repository_commit_details 
      WHERE repository_id = $1 AND commit_sha = $2
    `;
    
    const result = await this.db.query(query, [repository_id, commit_sha]);
    return result.rows[0];
  }

  async deleteCommitsByRepository(repository_id) {
    const query = `DELETE FROM repository_commit_details WHERE repository_id = $1`;
    const result = await this.db.query(query, [repository_id]);
    return result.rowCount;
  }
}

module.exports = CommitDetailsModel;
