import { getDatabase } from '../index';
import { Project } from '../../../types';
import { generateUUID } from '../../utils/uuid';
import { now } from '../../utils/datetime';

export async function createProject(
  userId: string,
  title: string,
  tags: string[] = [],
  status: Project['status'] = 'in_progress',
  coverImageUri?: string
): Promise<Project> {
  const db = getDatabase();
  const project: Project = {
    id: generateUUID(),
    title,
    status,
    tags,
    coverImageUri,
    createdAt: now(),
    updatedAt: now(),
  };

  await db.runAsync(
    `INSERT INTO projects (id, user_id, title, status, tags, cover_image_uri, created_at, updated_at)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
    [
      project.id,
      userId,
      project.title,
      project.status,
      JSON.stringify(project.tags),
      project.coverImageUri || null,
      project.createdAt,
      project.updatedAt,
    ]
  );

  return project;
}

export async function getProject(id: string): Promise<Project | null> {
  const db = getDatabase();
  const row = await db.getFirstAsync<any>(
    'SELECT * FROM projects WHERE id = ?',
    [id]
  );

  if (!row) return null;

  return {
    id: row.id,
    title: row.title,
    status: row.status,
    tags: JSON.parse(row.tags),
    coverImageUri: row.cover_image_uri || undefined,
    createdAt: row.created_at,
    updatedAt: row.updated_at,
  };
}

export async function getAllProjects(userId: string): Promise<Project[]> {
  const db = getDatabase();
  const rows = await db.getAllAsync<any>(
    'SELECT * FROM projects WHERE user_id = ? ORDER BY updated_at DESC',
    [userId]
  );

  return rows.map(row => ({
    id: row.id,
    title: row.title,
    status: row.status,
    tags: JSON.parse(row.tags),
    coverImageUri: row.cover_image_uri || undefined,
    createdAt: row.created_at,
    updatedAt: row.updated_at,
  }));
}

export async function updateProject(
  id: string,
  updates: Partial<Omit<Project, 'id' | 'createdAt' | 'updatedAt'>>
): Promise<void> {
  const db = getDatabase();
  const project = await getProject(id);
  if (!project) throw new Error('Project not found');

  const updatedProject = {
    ...project,
    ...updates,
    updatedAt: now(),
  };

  await db.runAsync(
    `UPDATE projects
     SET title = ?, status = ?, tags = ?, cover_image_uri = ?, updated_at = ?
     WHERE id = ?`,
    [
      updatedProject.title,
      updatedProject.status,
      JSON.stringify(updatedProject.tags),
      updatedProject.coverImageUri || null,
      updatedProject.updatedAt,
      id,
    ]
  );
}

export async function deleteProject(id: string): Promise<void> {
  const db = getDatabase();
  await db.runAsync('DELETE FROM projects WHERE id = ?', [id]);
}

export async function getProjectsByStatus(userId: string, status: Project['status']): Promise<Project[]> {
  const db = getDatabase();
  const rows = await db.getAllAsync<any>(
    'SELECT * FROM projects WHERE user_id = ? AND status = ? ORDER BY updated_at DESC',
    [userId, status]
  );

  return rows.map(row => ({
    id: row.id,
    title: row.title,
    status: row.status,
    tags: JSON.parse(row.tags),
    coverImageUri: row.cover_image_uri || undefined,
    createdAt: row.created_at,
    updatedAt: row.updated_at,
  }));
}
